Jason Law
Jason Law

Reputation: 1015

What does "non-block-structured locking" mean?

I am reading Java Concurrency in Practice. In 13.1 Lock and ReentrantLock, it says:

Why create a new locking mechanism that is so similar to intrinsic locking? Intrinsic locking works fine in most situations but has some functional limitations— it is not possible to interrupt a thread waiting to acquire a lock, or to attempt to acquire a lock without being willing to wait for it forever. Intrinsic locks also must be released in the same block of code in which they are acquired; this simplifies coding and interacts nicely with exception handling, but makes non-block-structured locking disciplines impossible.

What does "non-block-structured locking" mean? I think it means that you can lock in one method, unlock in another method, like Lock, but intrinsic locks must be released in the same block of code in which they are acquired. Am I right?

But the Chinese version of that book translates "block" to "阻塞". Is it an error?

Upvotes: 1

Views: 233

Answers (1)

Stephen C
Stephen C

Reputation: 718798

Block structured locking means that the pattern for acquiring and releasing locks mirrors the lexical code structure. Specifically, a section of code that acquires a lock is also responsible for releasing it; e.g.

Lock lock = ...
lock.acquire();
try {
    // do stuff
} finally {
    lock.release();
}

The alternative ("non-block-structured locking") simply means that the above constraint does not apply. You can do things like acquiring a lock in one method and releasing it in a different one. Or (hypothetically) even pass the lock to another thread to release1. The problem is that this kind of code is a lot harder to get correct, and a lot harder to analyze than the examples like the above.

1 - Beware. If you pass acquired locks between threads, you are liable to run into memory anomalies or worse. Indeed, I'm not even sure that it is legal in Java.


The "block structure" referred to in the quoted text is clearly talking about the lexical structure of the code, as per the Wikipedia article on the topic Block (programming). If the Chinese version of Java Concurrency in Practice uses characters that mean "blocking" in the sense of Blocking (programming), that is a mistranslation.

Upvotes: 5

Related Questions