user1097772
user1097772

Reputation: 3549

Active waiting replacement - Is my approach correct by design?

I am getting rid of waiting:

 public void run() {
    while(!running) {} //active waiting
    //some action after running is true

 }

My code:

class MyThread implements Runnable {

      protected boolean running = false;
      public Object lock = new Object();

      @Override
      public void run() {
        while(!running) {

          synchronized(lock) {
            try {
              lock.wait();
            } catch (InterruptedException e) {
               e.printStackTrace();
            }

         }//end lock

        }

        //main job which will be done when the flag running is true

      }//end run

      public void managerStateChanged (Manager m) {

        if(m.getState() == 1) {
          this.running = true;
          synchronized(lock) {
            lock.notify(); 
          }
        }
      }          
    }

    class Manager {

     protected MyThread listener = null;
     protected int state = 0;

     public int getState() { return state; }

     public void registerListener(MyThread l) {
        listener = l;
     }

     public void managerStateChanged() {
       if(listener != null) {
         listener.managerStateChanged(this);
       }
     }
    }

Edit:
1) For all - be careful when using this, both wait() and notify() must be wrapped in synchronized block otherwise it will raise IlegalMonitorException, when you have it in your code and still getting this exception search again, there is probably called another notify somewhere else without this synchronized block. Thank to the comments.
2) I modified the question since my code was ok but sh** happens and I forgot delete something somewhere. This is working fine. The question is my implementation correct?
There are some points that I am not fully sure about:

Are my guesses about this right? Is the code clear? Didn't I miss something what should be treated better? I hope not. Thanks for replies.

Upvotes: 3

Views: 122

Answers (0)

Related Questions