Java keyword synchronized


Thesynchronizedkeyword is used for code blocks and methods where thread-safe matters and for multi-threaded (concurrent) programming. A synchronized method or a synchronized statement can be executed by only one thread at a time.

The syntax for asynchronizedmethodis as follows:

<method modifier>synchronized <method signature> {

// synchronized code block

}

The syntax for asynchronizedstatementis as follows:

synchronized (expression) {

// synchronized code block

}

Synchronized keyword in Java has to do with thread-safety, that is, when multiple threads read or write the same variable.
This can happen directly (by accessing the same variable) or indirectly (by using a class that uses another class that accesses the same variable).

The synchronized keyword is used to define a block of code where multiple threads can access the same variable in a safe way.

Deeper

Syntax-wise thesynchronizedkeyword takes anObjectas it's parameter (calleda lock object), which is then followed by a{ block of code }.

  • When execution encounters this keyword, the current thread tries to "lock/acquire/own" (take your pick) thelock objectand execute the associated block of code after the lock has been acquired.

  • Any writes to variables inside the synchronized code block are guaranteed to be visible to every other thread that similarly executes code inside a synchronized code block using the samelock object.

  • Only one thread at a time can hold the lock, during which time all other threads trying to acquire the samelock objectwill wait (pause their execution). The lock will be released when execution exits the synchronized code block.

Synchronized methods:

Addingsynchronizedkeyword to a method definition is equal to the entire method body being wrapped in a synchronized code block with thelock objectbeingthis(for instance methods)andClassInQuestion.getClass()(for class methods).

- Instance method is a method which does not havestatickeyword.
- Class method is a method which hasstatickeyword.

Technical

Without synchronization, it is not guaranteed in which order the reads and writes happen, possibly leaving the variable with garbage.
(For example a variable could end up with half of the bits written by one thread and half of the bits written by another thread, leaving the variable in a state that neither of the threads tried to write, but a combined mess of both.)

It is not enough to complete a write operation in a thread before (wall-clock time) another thread reads it, because hardware could have cached the value of the variable, and the reading thread would see the cached value instead of what was written to it.

Conclusion

Thus in Java's case, you have to follow the Java Memory Model to ensure that threading errors do not happen.
In other words: Use synchronization, atomic operations or classes that use them for you under the hoods.

Related Articles

post a comment