What does ‘synchronized’ mean?

Technology CommunityCategory: JavaWhat does ‘synchronized’ mean?
VietMX Staff asked 3 years ago

The synchronized keyword is all about different threads reading and writing to the same variables, objects and resources. The synchronized keyword is one of the tools that make your code thread safe.

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. Synchronized methods can’t be called in the same time from multiple threads.

So simply speaking 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.