Search code examples
javasynchronize

Am I properly implementing Java's synchronized construct?


I'm kind of confused about how to implement synchronized blocks in Java.

Here is an example situation:

public class SlotWheel extends Thread implements ActionListener
{
  private int currentTick; // This instance variable is modified in two places

  private synchronized void resetCurrentTicks()
  {
    currentTick = 0;
  }

  private synchronized void incrementCurrentTicks()
  {
    ++currentTick;
  }

  public void actionPerformed(ActionEvent e)
  {
    resetCurrentTicks();
  }
}

While the program is running, it's possible that a user clicks a button which invokes actionPerformed which then calls resetCurrentTicks. At the same time, the running thread is calling incrementCurrentTicks on each loop iteration.

Because I'm still new to Java and programming, I'm not sure if my implementation is protecting currentTick from becoming corrupted.

I have this feeling that my implementation would only work if incrementCurrentTicks were to be called in actionPerformed and in the running thread, but because I'm manipulating currentTick from different methods, my implementation is wrong.


Solution

  • Looks ok.

    See http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

    It is not possible for two invocations of synchronized methods on the same object to interleave

    Of course you should consider whether it is the GUI thread trying to mess with the ticks or not. In your simple case it's probably ok, but in a more complex case you might want to push the "work" out of the GUI thread.