multithreading - Java infinite loop performance -


i have thread has work when circumstance comes in. otherwise iterates on empty infinite loop:

public void run() {     while(true) {         if(ball != null) {              // calculations         }     } } 

does affect performance when loop nothing has check if has calculation every iteration? creating thread when needed not option me, because class implements runnable visual object has shown time.

edit: following solution? or better use different method (concerning performance)?

private final object standby = new object();  public void run() {     while(true) {         synchronized (standby) {             while(ball != null)  // should use while or if here?                 try{ standby.wait() }                 catch (interruptedexception ie) {}         }         if(ball != null) {              // calculations         } }  public void handlecollision(ball b) {     // more code..     ball = b;     synchronized (standby) {         standby.notify();     } } 

you might want consider putting thread sleep , waking when 'ball' variable becomes true. there multiple ways of doing this, using low level, wait , notify statements using java.util.concurrent classes provide less error prone way of doing this. have @ documentation condition interface. data structure blockingqueue solution.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -