What does synchronized()/wait()/notifyAll() do in Java? [duplicate] What does synchronized()/wait()/notifyAll() do in Java? [duplicate] multithreading multithreading

What does synchronized()/wait()/notifyAll() do in Java? [duplicate]


The synchronized keyword is used to keep variables or methods thread-safe. If you wrap a variable in a synchronized block like so:

synchronized(myVar) {    // Logic involing myVar}

Then any attempts to modify the value of myVar from another thread while the logic inside the synchronized block is running will wait until the block has finished execution. It ensures that the value going into the block will be the same through the lifecycle of that block.


This Java Tutorial can probably help you understand what using synchronized on an object does.

When object.wait() is called it will release the lock held on that object (which happens when you say synchronized(object)), and freeze the thread. The thread then waits until object.notify() or object.notifyAll() is called by a separate thread. Once one of these calls occurs, it will allow any threads that were stopped due to object.wait() to continue. This does not mean that the thread that called object.notify() or object.notifyAll() will freeze and pass control to a waiting thread, it just means these waiting threads are now able to continue, whereas before they were not.


When used like this:

private synchronized void someMehtod()

You get these effects:

1. First, it is not possible for two invocations of synchronized methods on the same object to interleave. 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.

2. 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. This guarantees that changes to the state of the object are visible to all threads.

(Taken from here)

You get a similar effect when you use a synchronized block of code:

private void someMethod() {  // some actions...  synchronized(this) {    // code here has synchronized access  }  // more actions...}

As explained here