synchronized is a keyword.
It marks a critical section. A critical section is where one and only one thread is executing. So to enter into the marked code the threads are synchronized, only one can enter, the others have to wait. For more information see Synchronizing Threads Methods or .
synchronized keyword can be used in two ways:
- Create a
- Mark a method
synchronized block is marked as:
|Code section 1: Synchronized block.
The syntax to mark a method
|Code section 2: Synchronized method.
The synchronization is always associated to an object. If the method is static, the associated object is the class. If the method is non-static, the associated object is the instance. While it is allowed to declare an
abstract method as
synchronized, it is meaningless to do so since synchronization is an aspect of the implementation, not the declaration, and abstract methods do not have an implementation.
As an example, we can show a thread-safe version of a singleton:
|Code listing 1: Singleton.java