Patrick Wallace
Patrick Wallace

Reputation: 91

Java - is this missed signal solution ok?

I've created a game and I want a player to be removed after sitting out for a length of time. A runnable PlayerRemover class contains an instance of a runnable GameTimer class. The PlayerRemover creates a GameTimer thread which times down or is stopped manually, after which it notifies the PlayerRemover thread continue.

I was concerned that a signal could be missed if notify() is called before wait(), so I decided to make the GameTimer thread notify until PlayerRemover thread sets a boolean variable in GameTimer to false.

I looked for a couple of solutions to missed signal online and this wasn't mentioned, and using while loops with atomic blocks of code is making me wonder if there's a good reason for that.

My code is running fine but will problems arise from this method? Is there a better more standard way to do this?

Appreciate the help, thanks!

public class PlayerRemover implements Runnable
{
  private final GameTimer timer;
  private final int seat;
  private final BlackjackPlayer p;
  private boolean wasSignalled;

  public PlayerRemover(TableFrame gui, GameTimer t)
  {
    timer = t;
    seat = gui.getTablePanel().getSeatIndex() ;
    p = gui.getTablePanel().getBlackjackPlayer();
    wasSignalled = false;
  }        

  @Override
  public void run()
  {
     Thread timerThread = new Thread(timer);
     timerThread.start();

     synchronized(timerThread)
     {    
       while (g[seat] != null && p.getState() == State.SITTING_OUT &&          timer.getSecondsLeft() > 0)
       {
           try {
               timerThread.wait();
           } catch (InterruptedException ex) {
               Logger.getLogger(TableCoord.class.getName()).log(Level.SEVERE, null, ex);
           }
       }
     }  

     timer.setSignalRecieved();
     timer.stopTimer();

     if (g[seat] != null && timer.getSecondsLeft() == 0)
     {
       removePlayer(p,seat);
       updateAllGUIs();
     }    
  }        
}



public class GameTimer implements Runnable {

private int secondsLeft; 
private boolean timerStop; 
private boolean doNotify;
private boolean signalReceived;

/**
* Creates a timer with a given number of seconds on the clock.
*/
public GameTimer(int seconds,boolean notifyThis)
{      
  secondsLeft = seconds;
  timerStop = false; 
  doNotify = notifyThis;
  signalReceived = false;
}

public GameTimer(int seconds)
{     
  secondsLeft = seconds;
  timerStop = false; 
  doNotify = false;
}

/**
* Stops timer permanently 
*/
public void stopTimer()
{
  timerStop = true;
}

public int getSecondsLeft()
{
   return secondsLeft;   
}         

public boolean getTimerStop()
{
  return timerStop;
 }         

public void setSignalRecieved()
{
 signalReceived = true;
}



 @Override
 public void run()
 {
   // While there timer is still counting down or all players finish 
   // their actions.
    while (!timerStop)
    {    
      // Wait 1 second  
      try
      {
       Thread.sleep(1000);
      }
      catch (Exception e)
      {
        System.out.println("Error: " + e.toString());
      }  

      //decrement timer 1 second
       secondsLeft--;

      if (secondsLeft <= 0)
      {
       timerStop = true;
      } 
    } 

    timerStop= true;
    if (doNotify)
    {  
     while (!signalReceived) 
    {    
       synchronized(this)
       {
         notify();
         try
         {
           Thread.sleep(100);
         }
         catch (Exception e)
         {
           System.out.println("Error: " + e.getMessage());
         }    
       }
     } 
   }
  }
 }

Upvotes: 2

Views: 132

Answers (1)

Denis Iskhakov
Denis Iskhakov

Reputation: 344

For the majority of tasks wait() and notify() methods are usually too low-level and error prone. One of the easy and high-level ways to schedule tasks is the ScheduledExecutorService

An example from its JavaDoc demonstrates both fixed rate repeatable task and one shot task:

Here is a class with a method that sets up a ScheduledExecutorService to beep every ten seconds for an hour:

import static java.util.concurrent.TimeUnit.*;


class BeeperControl {
   private final ScheduledExecutorService scheduler =
     Executors.newScheduledThreadPool(1);

   public void beepForAnHour() {
     final Runnable beeper = new Runnable() {
       public void run() { System.out.println("beep"); }
     };
     final ScheduledFuture<?> beeperHandle =
       scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
     scheduler.schedule(new Runnable() {
       public void run() { beeperHandle.cancel(true); }
     }, 60 * 60, SECONDS);
   }
 }

Upvotes: 1

Related Questions