Assalomu alaykum, yordam.uz saytimizga xush kelibsiz.
Bu saytda o`zingizni qiziqtirgan savollarga javob olishingiz va o`z sohangiz bo`yicha savollarga javob berishingiz mumkin. Bizning Oilamizga a'zo bo`lganingiz uchun chuqur Minnatdorchilik bildiramiz !!!

Javada tugamaydigan thread yaratishda muammo

+1 ovoz
157 marta ko‘rilgan
so‘radi 12 oktabr, 18 SARVARBEK (355 bal)
tahrirlandi 12 oktabr, 18 SARVARBEK

Javada threadlar bilan ishlashda quyidagicha muammoga duch keldim.

Dastur ishga tushganda 'New thread' yaratiladi va o'zini ishini boshlaydi. 'New thread' internetdan doimiy ma'lumotlarni qabul qiladi, qayta ishlaydi va 'UI Thread'ga informatsiyalani uzatib turadi. Muammo shundaki, 'New thread' ishga tushgach 2-3 kun normal holatda ishlayapdi, keyin esa hech qanday vazifa bajarmayapdi (na xatolik beradi, na qotib qoladi, hech qanday reaksiya yo'q). Quyida 'New thread' ning realizatsiya kodi keltirilgan:

package SeismicStation;

import ...

public class MySeedlinkReader implements Runnable {
    private SeedlinkReader seedlinkReader;
    private IDataRecordProgress onreceiverrecord;
    private String host;
    private int port;
    private int timeoutSecond;
    private volatile boolean isActive;

    public MySeedlinkReader(IDataRecordProgress onreceiverrecord, String host, int port, int timeoutSecond) {
        this.onreceiverrecord = onreceiverrecord;
        this.host = host;
        this.port = port;
        this.timeoutSecond = timeoutSecond;
        isActive = true;
    }

    //...

    private void startSeedlink() {
        while (isActive) {
            try {
                if (seedlinkReader.isConnected() && seedlinkReader.hasNext()) {
                    try {
                        SeedlinkPacket packet = seedlinkReader.next();
                        DataRecord dr = packet.getMiniSeed();
                        MyGlobalClass.log(Level.INFO,"Receive datarecord:\n"+dr.info());
                        onreceiverrecord.onDataRecordProgress(dr);
                    } catch (IOException e) {
                        reconnectSeddlink();
                    } catch (SeedlinkException | SeedFormatException e) {
                        e.printStackTrace();
                    }
                } else {
                    reconnectSeddlink();
                }
            } catch (IOException e) {
                e.printStackTrace();
                reconnectSeddlink();
            }
            cleanJunkData();
        }
        seedlinkReader.close();
    }

    private void reconnectSeddlink() {
        while (!seedlinkReader.isConnected()) {
            try {
                seedlinkReader.reconnect();
            } catch (IOException | SeedlinkException e) {
                e.printStackTrace();
            }
        }
    }

    private void cleanJunkData() {
        System.gc();
    }

    public void stopSeedlink() {
        isActive = false;
    }

    @Override
    public void run() {
        startSeedlink();
    }
}

'New Thread'ni ishga tushirish kodi:

private void startSeedlink() {
    if (MyGlobalClass.licenseState() == TypeLicense.OK) {
        mySeedlinkReader = new MySeedlinkReader(this, SeedlinkReader.DEFAULT_HOST, SeedlinkReader.DEFAULT_PORT, SeedlinkReader.DEFAULT_TIMEOUT_SECOND);
        try {
            mySeedlinkReader.registerStations(stationList);
            new Thread(mySeedlinkReader).start();//New Threadni ishga tushirish
            MyGlobalClass.log(Level.INFO,"Seedlink is started");
        } catch (IOException | SeedlinkException e) {
            e.printStackTrace();
        }
    } else {
        MyGlobalClass.showMessage(Alert.AlertType.ERROR, "License is not found");
    }
}

Muammo nimadaligini topolmayapman.

Savollar:

1) 'New Thread' ning ishi qanday ketayotganligini (to'xtab qolmaganligini) qanday qilib tekshirib turishim mumkin?

2) Tugamaydigan thread ('New Thread') to'g'ri yaratilganmi yoki 'New Thread'ni boshqacha tarzda realizatsiya qilishim kerakmi (ya'ni while(true) dan ko'ra yaxshiroq variant bormi demoqchiman) ?

Javob uchun oldindan rahmat

1 ta javob

0 ovoz
javob berdi 15 oktabr, 18 Jasur320 (71 bal)
tanlangan 20 oktabr, 18 SARVARBEK
 
Eng yaxshi javob

Assalomu alaykum.

1) Thread larni holatini doimiy kuzatish(monitor) qilish uchun manimcha "Timer" dan foydalansangiz bo'ladi.

Misol (javax.swing.Timer;):

Timer progressMonitor = new Timer(60000, new ActionListener() { //every minute it will check current status of  current thread group

      public void actionPerformed(ActionEvent event)

        { 

                       Set<Thread> threadSet = Thread.getAllStackTraces().keySet();

                       for ( Thread t : threadSet){

                           if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup()){

                               

                               System.out.println("Thread :"+t+":"+"state:"+t.getState());

                          

                              }

                        }

                        

                        }

     });

java.util.Timer orqali qilsangiz ham bo'ladi, qanday ishlatish bu yerda ko'rsatilgan:
https://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java

 2) Qaysi bir "inifinite loop"ni ishlatishizni farqi yo'q, hammasi programmani to'htatmagunizcha takrorlanishni t'minlb beradi, man while(true) ishlataman el qatori:

while (true) {

        // do something

    }

for (;;) {

        // do something

    }

do {

        // do something

    } while (true);

Yana bir maslahat, bu sikl ichida har safar Garbage Collectorni chaqirvotgan ekansiz, shuni iloji bo'sa olib tashash kerak, bo'lmasa kamroq chaqirdigan qilish kerak. Quyidagi fikr va ma'lumotlarni bir o'qib chiqin:

https://stackoverflow.com/questions/2414105/why-is-it-bad-practice-to-call-system-gc 

izoh qoldirdi 15 oktabr, 18 SARVARBEK (355 bal)
Javobingiz uchun rahmat. https://stackoverflow.com/questions/2414105/why-is-it-bad-practice-to-call-system-gc   - dagi fikrlarni o'qib chiqdim, bugni ham ko'rdim. Garbage Collectorni olib tashlashim kerak ekan. Uni olib tashlashim mumkin, lekin dastur ishlashi natijasida musor xotiralar ko'payib ketsa (masalan 1 hafta ishlagandan so'ng), bu narsa dastur ishlashiga ta'sir ko'rsatmaydimi? Garbage Collectorsiz xotirani qanday tozalashni maslahat berasiz yoki bu muammoni JVMni o'ziga qo'yib berganim ma'qulmi?
izoh qoldirdi 16 oktabr, 18 Jasur320 (71 bal)
Programmani ishg tushirib bir necha kun 2-3 soat oraliqda top(*nix OSlarda),jmap tool lar yordamida monitor qilin :
top -p PID
jmap -heap PID

Agar JVM ni o'zi GCni  chaqirishi yetarli bo'lmay HEAP SPACE to'lib qolsa, quyidagi linklarda programmni  ishgtushirish paytida qo'llanilish mumkin bo'lgan hintlar keltirilgan:

http://www.fasterj.com/articles/oraclecollectors1.shtml
https://jelastic.com/blog/tuning-garbage-collector-java-memory-usage-optimization/

Assalomu alaykum, yordam.uz saytimizga xush kelibsiz.

Bu saytda o`zingizni qiziqtirgan savollarga javob olishingiz va o`z sohangiz bo`yicha savollarga javob berishingiz mumkin.

Bizning Oilamizga a'zo bo`lganingiz uchun chuqur Minnatdorchilik bildiramiz !!!

Telegram kanal YordamUzRss

...