Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What does 'synchronized' mean?

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?
by

3 Answers

akshay1995
The synchronized keyword prevents concurrent access to a block of code or object by multiple threads. All the methods of Hashtable are synchronized, so only one thread can execute any of them at a time.

When using non-synchronized constructs like HashMap, you must build thread-safety features in your code to prevent consistency errors.
RoliMishra
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).
sandhya6gczb
The synchronized keyword is all about different threads reading and writing to the same variables, objects and resources. This is not a trivial topic in Java, but here is a quote from Sun:

synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.

In a very, very small nutshell: When you have two threads that are reading and writing to the same 'resource', say a variable named foo, you need to ensure that these threads access the variable in an atomic way. Without the synchronized keyword, your thread 1 may not see the change thread 2 made to foo, or worse, it may only be half changed. This would not be what you logically expect.

Login / Signup to Answer the Question.