Day 2: Beyond Intrinsic Locks

Beyond Intrinsic Locks

        Day 1 covered Java’s Thread class and the intrinsic locks built into every Java

object. For a long time this was pretty much all the support that Java provided  for concurrent programming. Java 5 changed all that with the introduction    of java.util.concurrent. Today we’ll look at the enhanced locking mechanisms it   provides.

        Intrinsic locks are convenient but limited.

• There is no way to interrupt a thread that’s blocked as a result of trying

    to acquire an intrinsic lock.

• There is no way to time out while trying to acquire an intrinsic lock.

• There’s exactly one way to acquire an intrinsic lock: a synchronized block.

synchronized(object) {
«use shared resources»
}

This means that lock acquisition and release have to take place in the

same method and have to be strictly nested. Note that declaring a method

as synchronized is just syntactic sugar for surrounding the method’s body

with the following:

synchronized(this)«method body»
}


        ReentrantLock allows us to transcend these restrictions by providing explicit lock

and unlock methods instead of using synchronized.

        Before we go into how it improves upon intrinsic locks, here’s how ReentrantLock

can be used as a straight replacement for synchronized :

Lock lock = new ReentrantLock();
lock.lock();
try {
«use shared resources»
} finally {
lock.unlock();
}


        The try ... finally is good practice to ensure that the lock is always released, no

matter what happens in the code the lock is protecting.




你可能感兴趣的:(ReentrantLock)