Java Programming/Keywords/synchronized
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 [1].
The synchronized
keyword can be used in two ways:
- Create a
synchronized
block - Mark a method
synchronized
A synchronized
block is marked as:
synchronized(<object_reference>){ // Thread.currentThread() has a lock on object_reference. All other threads trying to access it will // be blocked until the current thread releases the lock. }
The syntax to mark a method synchronized
is:
publicsynchronizedvoidmethod(){ // Thread.currentThread() has a lock on this object, i.e. a synchronized method is the same as // calling { synchronized(this) {...} }. }
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.
Singleton example
[edit | edit source ]As an example, we can show a thread-safe version of a singleton:
/** * The singleton class that can be instantiated only once with lazy instantiation */ publicclass Singleton{ /** Static class instance */ privatevolatilestaticSingletoninstance=null; /** * Standard private constructor */ privateSingleton(){ // Some initialisation } /** * Getter of the singleton instance * @return The only instance */ publicstaticSingletongetInstance(){ if(instance==null){ // If the instance does not exist, go in time-consuming // section: synchronized(Singleton.class){ if(instance==null){ instance=newSingleton(); } } } returninstance; } }