Does a thread release a lock when it finishes?

I have read in places that it isn't good programming practice to acquire a Lock object without the code following being enclosed in a try...finally block so the lock can be released even if an exception is thrown.

It might sound like a simple question: do all locks belonging to a thread automatically release when the thread finishes?

The reason I ask this question is that the program I am working on is such that once a thread acquires a lock, it should have no reason let it go until it finishes. Additionally, I'm new to using locks, so I'm wondering if there's any pitfalls I may not have considered. Do I have to worry about explicitly releasing locks in my code before the thread finishes, or can I leave it to the JVM, confident in the certain knowledge that other threads being blocked on all the active thread's locks will be activated as soon as the active thread stops?


Simple test may show you that lock is not released upon thread termination:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {
    public static void main(String[] args) {
        final Lock l = new ReentrantLock();

        Thread t = new Thread() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread()+": Acquire lock");
                l.lock();
                System.out.println(Thread.currentThread()+": Lock aquired: wait");
                LockSupport.parkNanos(1_000_000_000);
                System.out.println(Thread.currentThread()+"; Exiting");
            }
        };
        t.start();
        LockSupport.parkNanos(500_000_000);
        System.out.println(Thread.currentThread()+": Acquire lock");
        l.lock();
        System.out.println(Thread.currentThread()+"; Success!");
    }
}

Output:

Thread[Thread-0,5,main]: Acquire lock
Thread[Thread-0,5,main]: Lock aquired: wait
Thread[main,5,main]: Acquire lock
Thread[Thread-0,5,main]; Exiting
// "Success" is never written: stuck in dead-lock

So when the separate thread acquired the lock, then exited, lock cannot be taken by main thread.

链接地址: http://www.djcxy.com/p/29714.html

上一篇: 向后兼容Angular UI Bootstrap 0.14.0

下一篇: 线程完成时是否释放一个锁?