top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the purpose of synchronized keyword?

+3 votes
190 views
What is the purpose of synchronized keyword?
posted Jul 15, 2015 by Karthick.c

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

The Java 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.
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".

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

Explanation:
we have a counter that needs to be incremented at random points in time by different threads.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.

answer Mar 22, 2016 by Shivam Kumar Pandey
...