When should a method be declared synchronized?

synchronized method
java synchronized static method
java synchronized method vs block
java synchronized keyword
java synchronized lock
java synchronized variable
what does 'synchronized' mean in java
synchronized(this) vs synchronized(object)

Following is a, simple, working program which uses two threads to print a counter:

public class SynchronizedCounter implements Runnable {

    private static int i = 0;

    public void increment() { i++; }
    public int getValue() { return i; }  

    @Override
    public void run() {
        for( int i = 0; i < 5; i++ ) {
            synchronized( this ) {
                increment();
                System.out.println( Thread.currentThread().getName() + " counter: " + this.getValue() );
            }
        }
    }

    public static void main( String[] args ) {

        ExecutorService executorService = Executors.newFixedThreadPool( 2 );
        SynchronizedCounter synchronizedCounter = new SynchronizedCounter();
        executorService.submit( synchronizedCounter );
        executorService.submit( synchronizedCounter );  
        executorService.shutdown();

    }

}

The output is as expected - the two threads display counter in order.

If increment() and getValue() are declared as synchronized and synchronized block code is commented, the output manifests visibility and race problems.

As increment() and getValue() are not declared as synchronized and by, just, using a synchronized block(passing a monitor object) if synchronization could be achieved, in what circumstances should they be declared as synchronized?


Your increment() method uses i++ which is in fact substituted by 3 instructions. If that method is not declared as synchronized then several threads may execute it at the same time which will lead to race conditions and incorrect results.

If increment() and getValue() are declared as synchronized and synchronized block code is commented, the output manifests visibility and race problems.

There are no race conditions in this case. You see different results because now increment() and getValue() are not executed atomically (by atomically I mean two methods as one synch block) and while one thread called increment() and is about to call getValue() another thread also called increment().

So you need to make increment() and getValue() synchronized if you are planning to call them outside of synchronized block in your run method (and because they are declared as public there is a possibility to make such calls).

Can we synchronize a run() method in Java?, , it automatically acquires the lock for that object and releases it when the thread completes its task. These methods must be synchronized to ensure that the data remains in a consistent state throughout the life of the program. You can declare that a method must be synchronized with the synchronized keyword. Synchronizing method calls is covered in the Threads of Control lesson. Take particular note of the page titled Synchronization


Declare a method synchronized when you need the semantics of a synchronized block around the body of the method.

synchronized void increment() {
  ...
}

is exactly the same as:

void increment() {
  synchronized (this) { ... }
}

The thing about doing that in the code above is that you no longer execute the increment() and getValue() methods atomically: another thread can nip in and execute the methods in between the calls of your thread:

Thread 1             Thread 2

increment()
                     increment()
                     getValue()
getValue()

This is possible, but two threads can't execute increment() (or getValue()) at the same time, because they are synchronized (*).

On the other hand, synchronizing around the calls as in the code in the question means that the two calls are executed atomically, so the two threads can't interleave:

Thread 1             Thread 2

increment()
getValue()
                     increment()
                     getValue()

(*) Actually, they can both be executing the method at the same time. It's just that all but one of the threads will be waiting at the synchronized (this).

Synchronization in Java, Why would you use a synchronized block vs synchronized method? When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object.


In your code, the class itself is not thread safe and it is up to the client (your run method) to ensure thread safety.

If you want to make the class thread safe such that clients don't need to do anything particular to use it, it should have proper synchronization mechanisms and propose "higher level" method that can run atomic operation on a combination of operations if necessary.

Think of AtomicInteger, for example, which has an incrementAndGet() method that would provide a superior approach. Your run method would then become:

for( int i = 0; i < 5; i++ ) {
  int newValue = counter.incrementAndGet();
  System.out.println(Thread.currentThread().getName() + " counter: " + newValue );
}

Why is synchronized block better than synchronized method , Your increment() method uses i++ which is in fact substituted by 3 instructions. If that method is not declared as synchronized then several  No two threads can concurrently execute synchronized methods on the same object. Methods declared synchronized should not be recursive, since the object lock will not allow new invocations of the method. Synchronized methods can only call other synchronized methods directly. Inside a synchronized method, one can assume that no other threads are currently executing any other methods in the same class. 13.13


Java synchronized method lock on object, or method?, But it should be 2 by the effect of both threads. That's why we need to synchronize the access to shared variable i. Java is multi-threaded language where multiple  8.4.3.6 synchronized Methods. A synchronized method acquires a monitor (??17.1) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used.


When should a method be declared synchronized?, This article discusses thread synchronization of methods, static methods, and This quick article will be an intro to using the synchronized block in Java. keyword in the method declaration to make the method synchronized:. No the internal methods do NOT need to declare as synchronized. As each method should work on an object independently as much as possible (encapsulation from OOP). So there might be some work that does not need atomicity. In those cases it’s useless to have method synchronized.


Method and Block Synchronization in Java, Synchronization in java thread with java synchronized method, synchronized block, static synchronization Here, we will discuss only thread synchronization. If you declare any method as synchronized, it is known as synchronized method. Given that it has to be an instance method to be abstract, there certainly is a reference which could be locked on. Concrete methods in abstract classes can still refer to this. However, that still doesn't mean that abstract classes should be able to be synchronized. Whether or not a method is synchronized is an implementation detail of