I understand that the synchronized keyword is used to prevent multiple threads from accessing the same chunk of code (either a whole method or a block of synched code within a method) at the same time, and that this helps prevent nasty things from occurring, such as deadlocks.
What I’m stumped on is when it is appropriate to use this mechanism: what rule of thumb(s) exist as to when a certain fragment of code should be thread-safe? The only instance I can think of is when the order of events for something happening are critical, but even then I can’t think of an actual, concrete, real-world example.
I’ve never written a synchronized method or block, and so “seeing the forest through the trees” is difficult for me, somehow. Any contextual examples are greatly appreciated! Thanks in advance.
Use
synchronizedwhen two or more threads need to modify the same resource, and you want to enforce that only one of them gets access to the resource at any given time. For example, when you have a set of variables that should be modified together.Here’s an example from the Java tutorial:
The whole section is quite enlightening: