Java读写锁问题

前几天在对HBase Client进行优过程中,需要扩展HTable,需要加一个Timer来对Client buffer进行定时的flush。由于HTable不是线程安全的,所以为扩展的HTable使用了Java ReentrantReadWriteLock来进行读写锁。在不同的方法中加了读锁或者写锁,从而导致了死锁的问题。

看了一下文档,Java的读写锁只能downgrading不能upgrading,导致死锁的问题就是upgrading导致的。

下面是一个锁upgrading导致死锁的例子:

 ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        lock.readLock().lock();
        try{
            System.out.println("Got a read lock");
            lock.writeLock().lock();//want to upgrade from read lock to write, here is the deadlock
            try{
                System.out.println("Got a write lock");
            } finally {
                lock.writeLock().unlock();
                System.out.println("Unlock a write lock");
            }
        } finally {
            lock.readLock().unlock();
            System.out.println("Unlock a read lock");
        }

下面是一个锁downgrading的例子:

ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        lock.writeLock().lock();
        try{
            System.out.println("Got a write lock");
            lock.readLock().lock();//Downgrade from write lock to read lock, it's ok.
            try{
                System.out.println("Got a read lock");
            } finally {
                lock.readLock().unlock();
                System.out.println("Unlock a read lock");
            }
        } finally {
            lock.writeLock().unlock();
            System.out.println("Unlock a write lock");
        }


你可能感兴趣的:(Java读写锁问题)