Since Java is a multithreaded system, you must often take care to prevent multiple threads from modifying an object
simultaneously in a way that might corrupt the object's state. Sections of code that must not be executed simultaneously are
known as critical sections. Java provides the synchronized statement to protect these critical sections. The syntax is:
synchronized ( expression ) {
statements
}
expression is an expression that must evaluate to an object or an array. The statements constitute the code of the critical
section and must be enclosed in curly braces. Before executing the critical section, the Java interpreter first obtains an
exclusive lock on the object or array specified by expression. It holds the lock until it is finished running the critical section,
then releases it. While a thread holds the lock on an object, no other thread can obtain that lock. Therefore, no other thread
can execute this or any other critical sections that require a lock on the same object. If a thread cannot immediately obtain the
lock required to execute a critical section, it simply waits until the lock becomes available.
Note that you do not have to use the synchronized statement unless your program creates multiple threads that share
data. If only one thread ever accesses a data structure, there is no need to protect it with synchronized. When you do
have to use synchronized, it might be in code like the following:
public static void SortIntArray(int[] a) {
// Sort the array a. This is synchronized so that some other thread
// cannot change elements of the array while we're sorting it (at
// least not other threads that protect their changes to the array
// with synchronized).
synchronized (a) {
// Do the array sort here...
}
}
The synchronized keyword is also available as a modifier in Java and is more commonly used in this form than as a
statement. When applied to a method, the synchronized keyword indicates that the entire method is a critical section. For
a synchronized class method (a static method), Java obtains an exclusive lock on the class before executing the method.
For a synchronized instance method, Java obtains an exclusive lock on the class instance. (Class and instance methods

No comments:
Post a Comment