multithreading - How to avoid busy spinning in Java -



multithreading - How to avoid busy spinning in Java -

i have multi-threaded application thread sends message thread. waiting thread polls message , reacts (locks handled). this:

waiting thread code:

while(true) { if(helloarrived()) system.out.println("got hello"); if(byearrived()) system.out.println("got bye"); if(stoparrived()) break; }

i want avoid cpu hogging technique , utilize else instead. ideas?

edit: actual code below:

blockingqueue<mail> killmemailbox = new linkedblockingqueue<mail>(); blockingqueue<mail> messagemailbox = new linkedblockingqueue<mail>(); public void run() { while(true) { if(killmemailbox.size() > 0) { break; } if(messagemailbox.size() > 0) { system.out.println(messagemailbox.poll()); } } } public void receivemail(mail mail) { //kill if(mail.from == -1) { killmemailbox.add(0); } else { //other seek { messagemailbox.put(mail); } catch(exception e) { system.out.println(e.getmessage()); } } }

the right way avoid utilize wait/notify mechanism implemented java.lang.object, or 1 of higher level concurrency mechanisms provided java class libraries:

semaphores, latches / cyclic barriers, blocking queues; e.g. classes implemented blockingqueue interface.

(pick mechanism best match specific use-case ...)

using thread.sleep not solution. while cut down cpu load (compared polling loop), flip-side cut down responsiveness.

i'm using blockingqueue now. maybe i'm doing incorrectly. added code above. see problem?

yea. using queue in way designed avoid blocking. that's wrong approach. should utilize take() (which block until entry becomes available) instead of poll(), , rid of code tests queue size.

your "killmemailbox" stuff seems designed allow stop waiting mail. should able implement using thread.interrupt. (an interrupt unblock take() phone call ...)

java multithreading mutex

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -