java multithreading: Threads and Locks

Threads and Locks

1. Synchronization

        The Java programming language provides various mechanisms for communication between threads. One of the most basic is synchronization , which is achieved by using monitors . Every object in Java is associated with a monitor, and threads can lock or unlock this monitor. Only one thread can lock the monitor at a time. Any other threads attempting to lock the monitor will be blocked until they acquire the lock permission for that monitor. A thread may lock a particular monitor multiple times; each unlock operation has the opposite effect of the lock operation.

        Synchronized code block: The Synchronized code block first calculates the reference to the specified object; then attempts to perform the lock operation on the monitor of the object, and does not continue to execute the content of the code segment until the lock operation is successfully completed. After the locking operation is complete, the body of the synchronized block is executed. If the body of the synchronized block has completed execution, either normally or abruptly due to an exception, the unlock operation for the currently locked monitor will be performed automatically.

        Synchronized method: When the Synchronized method is called, it will automatically perform the lock operation, and the method body will be executed only after the lock operation is successfully completed. If the method is an instance method (that is, non-static) , the locked monitor is the monitor of the instance (that is, the this object) that invoked the synchronized method. If the synchronization method is static , it locks the monitor of the Class object that defines the static method (Note: For the explanation of the Class object, please refer to http://www.importnew.com/21235.html). If the method body has been executed, whether it is a normal termination or an abnormal termination, the unlocking operation for the current monitor will be automatically executed.

        The Java programming language neither prevents nor needs to detect deadlock situations. Programs where multiple threads hold (directly or indirectly) locks on multiple objects should use traditional techniques to avoid deadlocks and, if necessary, create higher-level locking primitives that do not deadlock.

Other mechanisms, such as reading and writing volatile variables and using classes from the java.util.concurrent package, provide an alternative to synchronizing reads and writes.

 

2. Wait Sets and Notification

        In addition to having an associated monitor, each object has an associated wait group ( wait set ). A wait group is a group of threads.

When an object is first created, its wait group is empty. Basic operations such as adding threads to and removing threads from a wait group are atomic. For the operation of the waiting group only through the methods Object.wait, Object.notify and Object.notifyAll.

        The operation of the waiting group may also be affected by the interrupt status of the thread, and the interruption is handled by methods in the Thread class. In addition, Thread's methods sleep and join are characteristically derived from the wait and notify methods in the Object class.

2.1 Wait

        Wait actions occur when the wait( ) method is called, or wait(long millisecs) and wait(long millisecs, int nanosecs).

        NoteA call of wait(long millisecs) with a parameter of zero, or a call of wait(long millisecs, int nanosecs) with two zero parameters, is equivalent to an invocation of wait()

         A thread returns normally if it does not throw an InterruptedException .

          Suppose that object m's wait( ) method is executed in thread t, and n is the number of lock operations that thread t has not matched by an unlock operation on object m.

One of the following occurs:

  • If n is equal to 0, that is, thread t does not yet own the lock on target object m, then an IllegalMonitorStateException is thrown.
  • If the wait method with a time parameter is executed, and the nanosecs parameter is not in the range of 0-999999 or the millisecs parameter is negative, an IllegalArgumentException will be thrown.
  • If thread t is interrupted, then InterruptedException is thrown and thread t's interrupted status is set to false.
  • Otherwise, the following occurs
  1. Thread t is added to the wait set of object m and performs n unlock operations on m.
  2. Thread t does not execute any further instructions until thread t is removed from object m's wait set. Any of the operations listed below can remove thread t from object m's wait set, allowing thread t to resume running after a period of time.                                         
     --The notify method of object m is executed, and thread t is selected to be removed from the wait set.
     --The notifyAll method of object m is executed. --The interrupt operation was performed
     for thread t .
     --In the case of a wait method with a time parameter, an internal operation removes thread t from object m's wait set after at least millisecs milliseconds plus nanosecs nanoseconds have elapsed since the execution of the wait method.
     --An internal action by the implementation. Implementations are permitted, although not encouraged,to perform "spurious wake-ups", that is, to remove threads from wait sets and thus enable resumption without    explicit instructions to do so。
  3. Thread t performs n lock operations on object m.
  4. If thread t is removed from m's wait set due to an interruption in the second step, then thread t's interrupt status is set to false and the wait method throws InterruptedException.

 2.2 Notification

  Notification actions occur when the methods notify and notifyAll are called.

Suppose thread t executes the above method on target object m, and n is the number of lock operations that thread t has not matched by an unlock operation on object m. One of the following will occur:

  • If n is equal to 0, an IllegalMonitorStateException is thrown. thread t does not yet own the lock on target object m
  • If n is greater than 0, and the notify method is executed, and the wait set of the object m is not empty, a thread is selected to be removed from the wait set.
  • If n is greater than 0 and the notifyAll method is executed, all threads in the wait set of the m object will be removed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325874058&siteId=291194637