Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is synchronized statement used for?

What is the usage of synchronized statements?

like image 515
Johanna Avatar asked Aug 12 '09 18:08

Johanna


People also ask

When should synchronization be used?

Synchronization is usually needed when you are sharing data between multiple invocations and there is a possibility that the data would be modified resulting in inconsistency. If the data is read-only then you dont need to synchronize. In the code snippet above, there is no data that is being shared.

What is the purpose of synchronized block?

A Synchronized block is a piece of code that can be used to perform synchronization on any specific resource of the method. A Synchronized block is used to lock an object for any shared resource and the scope of a synchronized block is smaller than the synchronized method.


1 Answers

These are used for when you are building a program with many "threads". When main starts, it starts with one thread, which executes the steps in a sequence. You can start many more threads, which can then execute code at the same time. If you're executing the same code at the same time, things might behave in ways you don't want:

y = x+20;
// at this moment, before the next instruction starts, some other thread performs 
// the above step, which sets 'y' (an object property) to something different.
int b = y+10; // this would not be x+20, as you might expect.

What you want to do is put a 'lock' over this block of code, to make sure that no other thread can start executing any code that is "synchronized on" the variable y.

synchronized (y) {
    y = x+20;
    int b = y+10;
} // lock gets released here

Now, all other threads have to wait for whichever thread got there first to exit the block and release the lock, at which point another thread grabs the lock, enters the block of code, executes it, and releases the lock. Note that y has to be an object (Integer), not a primitive type.

You can also add 'synchronized' to methods, which synchronizes on 'this' (the instance object), or the class in the case of a static method.

Writing multi-threaded code is hard, because of problems like this. Synchronization is one tool, though it has one major problem - deadlocks. There is a lot of information online about deadlocks.

like image 174
mk. Avatar answered Sep 22 '22 03:09

mk.