Example & Tutorial understanding programming in easy ways.

What is use of synchronized keyword?

The synchronized keyword is an essential tool in concurrent programming in Java. Its overall purpose is to only allow one thread at a time into a particular section of code thus allowing us to protect, for example, variables or data from being corrupted by simultaneous modifications from different threads.

This article looks at how to use synchronized in Java to produce correctly functioning multithreaded programs. Other articles in this section look at other Java 5 concurrency facilities which have in fact superseded synchronized for certain tasks.

Using a synchronized block

At its simplest level, a block of code that is marked as synchronized in Java tells the JVM: "only let one thread in here at a time".

Imagine, for example, that we have a counter that needs to be incremented at random points in time by different threads. Ordinarily, there would be a risk that two threads could simultaneously try and update the counter at the same time, and in so doing currpt the value of the counter (or at least, miss an increment, because one thread reads the present value unaware that another thread is just about to write a new, incremented value). But by wrapping the update code in a synchronized block, we avoid this risk:

public class Counter {
  private int count = 0;
  public void increment() {
    synchronized (this) {
      count++;
    }
  }
  public int getCount() {
    synchronized (this) {
      return count;
    }
  }
}

That's the simple overview of the most common use of synchronized. However, it's worth understanding a little about what actually happens "under the hood" because there's actually a bit more to synchronized than that.


Read More →