Thread Lifecycle – Concurrency: Part I

22.4 Thread Lifecycle

Before diving into the lifecycle of a thread, a few important thread-related concepts should be understood.

Objects, Monitors, and Locks

In Java, each object has a monitor associated with it—including arrays. A thread can lock and unlock a monitor, but only one thread at a time can acquire the lock on a monitor. The thread that acquires the lock is said to own the lock and has exclusive access to the object whose monitor was locked. Any other threads trying to acquire the lock are blocked and placed in the entry set of the monitor until the lock is released. At that time, if the entry set is not empty, a blocked thread is allowed to acquire the lock at the discretion of the JVM, based on the thread scheduling policy in effect. The locking mechanism thus implements mutual exclusion (also known as mutex).

It should be made clear that programs should not make any assumptions about the order in which threads are granted ownership of a lock while waiting in the entry set of the monitor providing the lock. Thread state transitions for lock acquisition are explained later (p. 1388).

The locking mechanism on a monitor is referred to by various names in the literature: intrinsic lock, monitor lock, object-level lock, monitor, or just lock. Conceptually, the lock is on the object, and therefore we will refer to this locking mechanism provided by a monitor associated with an object as the object lock or just lock, when it is clear which lock is being referred to.

Classes also have a class lock (a.k.a. class-level lock) that is analogous to the object lock. Such a lock is actually a lock on the java.lang.Class object that represents the class at runtime in the JVM. Given a class A, the reference A.class denotes this unique Class object. The class lock can be used in much the same way as an object lock to implement mutual exclusion.

The following static method of the Thread class can be used to determine whether the current thread holds a lock on a specific object:

Click here to view code image

static boolean holdsLock(Object obj)

Leave a Reply

Your email address will not be published. Required fields are marked *