I have some questions regarding the usage and significance of the synchronized
keyword.
- What is the significance of the
synchronized
keyword? - When should methods be
synchronized
? - What does it mean programmatically and logically?
I have some questions regarding the usage and significance of the synchronized
keyword.
synchronized
keyword?synchronized
?
synchronized simple means no two threads can access the block/method simultaneously. When we say any block/method of a class is synchronized it means only one thread can access them at a time. Internally the thread which tries to access it first take a lock on that object and as long as this lock is not available no other thread can access any of the synchronized methods/blocks of that instance of the class.
Note another thread can access a method of the same object which is not defined to be synchronized. A thread can release the lock by calling
The
synchronized
keyword prevents concurrent access to a block of code or object by multiple Threads. By default, aHashtable
issynchronized
, so only one thread can access the table at a time.On usage of
non-synchronized
constructs likeHashMap
,you must build thread safety features in your code to prevent memory consistency errors.The
synchronized
keyword causes a thread to obtain a lock when entering the method, so that only one thread can execute the method at the same time (for the given object instance, unless it is a static method).This is frequently called making the class thread-safe, but I would say this is a euphemism. While it is true that synchronization protects the internal state of the Vector from getting corrupted, this does not usually help the user of Vector much.
Consider this:
Even though the methods involved are synchronized, because they are being locked and unlocked individually, two unfortunately timed threads can create a vector with two elements.
So in effect, you have to synchronize in your application code as well.
Because method-level synchronization is a) expensive when you don't need it and b) insufficient when you need synchronization, there are now un-synchronized replacements (ArrayList in the case of Vector).
More recently, the concurrency package has been released, with a number of clever utilities that take care of multi-threading issues.
Overview
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 the
synchronized
keyword takes anObject
as it's parameter (called a 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) the lock object and 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 same lock object.
Only one thread at a time can hold the lock, during which time all other threads trying to acquire the same lock object will wait (pause their execution). The lock will be released when execution exits the synchronized code block.
Synchronized methods:
Adding
synchronized
keyword to a method definition is equal to the entire method body being wrapped in a synchronized code block with the lock object beingthis
(for instance methods) andClassInQuestion.getClass()
(for class methods).- Instance method is a method which does not have
static
keyword.- Class method is a method which has
static
keyword.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.
To my understanding synchronized basically means that the compiler write a monitor.enter and monitor.exit around your method. As such it may be thread safe depending on how it is used (what I mean is you can write an object with synchronized methods that isn't threadsafe depending on what your class does).
synchronized is a keyword in Java which is used to make happens before relationship in multithreading environment to avoid memory inconsistency and thread interference error.