Java Synchronize


when to use synchronize?
synchronized should be used whenever shared data is being modifed. Shared data can be variables declared as static or data stored in request/session

what happens in unsynchronized code?
In the above situation if the code is not synchronized there is a possibility that 2 threads might try to modify the data simultaneously and the data might get corrupted.

what does synchronize do?
At any point of time only one thread can execute the Synchronized block of code. So no possibility of data corruption.

how to synchronize?
Synchronization always requires a Lock. Compiler allows the thread that has the Lock to enter the synchronized code. And it is only possible for one thread to have the Lock at a time. If 2 threads tries to get the Lock then only one succeeds and the second one will have to wait till the first one releases the Lock.

what is a Lock?
every object in java is created with one lock.

Code can be synchronized at method level or for few lines of code.
If code is synchronized at method level then by default the Threads will get a Lock on the class object of method.
Example:
public synchronized void modifyCommonData() {
...
}

If the code is synchronized at block of code level then the Lock of the object passed to synchronized will be used
Example:
String myOwnLock = "myOwnLock";
synchronized(myOwnLock) {
....
}

CAUTION:
Synchronized restricts simultaneous execution of the code by multiple threads. Basically the Threads wait in a Queue to get their chance to execute the synchronized code.
- So if a method does a lot of things then it is better to use the synchronized blocks than synchronizing the whole method.
- And it is not necessary to use synchronized for getMethods (if they are just reading the data)

No comments: