Synchronized MethodsThe Java programming language provides two basic synchronization idioms:
Synchronized MethodsAnd
Synchronized statements. The more complex of the two, synchronized statements, are described in the next section. This section is about synchronized methods.
To make a method synchronized, simply addsynchronized
Keyword to its declaration:
public class SynchronizedCounter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } public synchronized int value() { return c; }}
Ifcount
Is an instanceSynchronizedCounter
, Then making these methods synchronized has two effects:
- First, it is not possible for two invocations of synchronized methods on the same object To interleave. when one thread is executing a Synchronized Method for an object, all other threads that invoke synchronized methods for the same object block (suspend
Execution) until the first thread is done with the object.
- Second, when a synchronized method exits, it automatically establishes a happens-before relationshipAny subsequent invocationOf A Synchronized Method for the same object. This guarantees that changes to the state of the object are visible
To all threads.
Note that constructors cannot be synchronized-usingsynchronized
Keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object shoshould have access to it while
It is being constructed.
Warning:When constructing an object that will be shared between threads, be very careful that a reference to the object does not "leak" prematurely. For example, suppose you want to maintain
List
Called
instances
Containing every instance of class. You might be tempted to add the line
instances.add(this);
To your constructor. But then other threads can useinstances
To access the object before construction of the object is complete.
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 throughsynchronized
Methods.
(An important exception:final
Fields, which cannot be modified after the object is constructed, can be safely read through non-synchronized methods, once the object is constructed) This strategy is valid tive, but can present problems
Liveness, as we'll see later in this lesson.
Intrinsic locks and synchronizationsynchronization is built around an internal entity known as
Intrinsic lockOr
Monitor lock. (The API specification often refers to this entity simply as a "monitor. ") Intrinsic locks play a role in both aspects of synchronization: enforcing exclusive access to an object's state and establishing happens-before relationships that
Are essential to visibility.
Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields hasAcquireThe object's intrinsic lock before accessing them, and then
ReleaseThe intrinsic lock when it's done with them. A thread is said
OwnThe intrinsic lock between the time it has acquired the lock and released the lock. as long as a thread owns an intrinsic lock, no other thread can acquire the same lock. the other thread will block when it attempts to acquire the lock.
When a thread releases an intrinsic lock, a happens-before relationship is established between that action and any subsequent acquistion of the same lock.
Locks in synchronized methods
When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method's object and releases it when the method returns. the lock release occurs even if the return was caused by an uncaught exception.
You might wonder what happens when a static Synchronized Method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock forClass
Object associated with the class.
Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.
Synchronized statements
Another way to create synchronized code isSynchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:
public void addName(String name) { synchronized(this) { lastName = name; nameCount++; } nameList.add(name);}
In this example,addName
Method needs to synchronize changes
lastName
AndnameCount
, But also needs to avoid synchronizing invocations of other objects 'Methods. (invoking other objects 'Methods from synchronized code can create problems that are described in the section onliveness .)
Without synchronized statements, there wocould have to be a separate, unsynchronized method for the sole purpose of invokingnameList.add
.
Synchronized statements are also useful for improving concurrency with fine-grained synchronization. Suppose, for example, ClassMsLunch
Has two instance fields,
c1
Andc2
, That are never used together. all updates of these fields must be synchronized, but there's no reason to prevent an update of C1 from being interleaved with an update of C2-and doing so reduces concurrency by creating
Unnecessary blocking. Instead of using synchronized methods or otherwise using the lock associatedthis
, We create two objects solely to provide locks.
public class MsLunch { private long c1 = 0; private long c2 = 0; private Object lock1 = new Object(); private Object lock2 = new Object(); public void inc1() { synchronized(lock1) { c1++; } } public void inc2() { synchronized(lock2) { c2++; } }}
Use this idiom with extreme care. You must be absolutely sure that it really is safe to interleave access of the affected fields.
Reentrant Synchronization
Recall that a thread cannot acquire a lock owned by another thread. But a thread
CanAcquire a lock that it already owns. Allowing a thread to acquire the same lock more than once enablesReentrant Synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains
Synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code wowould Have To take into additional precautions to avoid having a thread cause itself to block.