Skip to content
Advertisement

How can I guarantee a thread is safely unlocking a lock upon termination, while all methods already handle it?

A server project, might run for very long time and create many threads. In the following code I ask myself do i have to protect the lock somehow in addition to an overall try catch in method setData(MyData data):

note: assuming its thread-safe, i am not really familiar with other reasons or natural disasters that may cause thread termination, like windows 7 limitations or so. (i am not greedy, using +-5 threads, but still)

public class MyFactory {

private ReadWriteLock rwl = new ReentrantReadWriteLock();
    private Lock readLock = rwl.readLock();
    private Lock writeLock = rwl.writeLock();
    
    private static MyFactory _instance = new MyFactory();
    private static Map<Integer, MyData> mapDatas = new HashMap<>();
    
    public static MyFactory getInstance() {
        return _instance;
    }
    
    
    public void setData(MyData data) {
        writeLock.lock();   
        try {
            mapData.put(...);
        } catch (Exception exc) {
            ...
        } finally {
            writeLock.unlock();
        }
    }

Advertisement

Answer

Assuming that you never expose the lock to other objects and you always use unlock the lock in a finally block, you are fine.

The reason is that the code in the finally block is always called if something happens in the try or catch blocks. Even if an Error is thrown this is true. These happen for example when you’re out of memory or there is a linkage error with some DLL. If something worse happens than an Error, that will likely also end your process and make the problem moot.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement