java.util.concurrent.locks.ReentrantReadWriteLock类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(12.0k)|赞(0)|评价(0)|浏览(151)

本文整理了Java中java.util.concurrent.locks.ReentrantReadWriteLock类的一些代码示例,展示了ReentrantReadWriteLock类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ReentrantReadWriteLock类的具体详情如下:
包路径:java.util.concurrent.locks.ReentrantReadWriteLock
类名称:ReentrantReadWriteLock

ReentrantReadWriteLock介绍

[英]An implementation of ReadWriteLock supporting similar semantics to ReentrantLock.

This class has the following properties:

  • Acquisition order

This class does not impose a reader or writer preference ordering for lock access. However, it does support an optional fairness policy. Non-fair mode (default) When constructed as non-fair (the default), the order of entry to the read and write lock is unspecified, subject to reentrancy constraints. A nonfair lock that is continuously contended may indefinitely postpone one or more reader or writer threads, but will normally have higher throughput than a fair lock.

Fair mode When constructed as fair, threads contend for entry using an approximately arrival-order policy. When the currently held lock is released, either the longest-waiting single writer thread will be assigned the write lock, or if there is a group of reader threads waiting longer than all waiting writer threads, that group will be assigned the read lock.

A thread that tries to acquire a fair read lock (non-reentrantly) will block if either the write lock is held, or there is a waiting writer thread. The thread will not acquire the read lock until after the oldest currently waiting writer thread has acquired and released the write lock. Of course, if a waiting writer abandons its wait, leaving one or more reader threads as the longest waiters in the queue with the write lock free, then those readers will be assigned the read lock.

A thread that tries to acquire a fair write lock (non-reentrantly) will block unless both the read lock and write lock are free (which implies there are no waiting threads). (Note that the non-blocking ReadLock#tryLock() and WriteLock#tryLock() methods do not honor this fair setting and will immediately acquire the lock if it is possible, regardless of waiting threads.)

  • Reentrancy

This lock allows both readers and writers to reacquire read or write locks in the style of a ReentrantLock. Non-reentrant readers are not allowed until all write locks held by the writing thread have been released.

Additionally, a writer can acquire the read lock, but not vice-versa. Among other applications, reentrancy can be useful when write locks are held during calls or callbacks to methods that perform reads under read locks. If a reader tries to acquire the write lock it will never succeed.

  • Lock downgrading

Reentrancy also allows downgrading from the write lock to a read lock, by acquiring the write lock, then the read lock and then releasing the write lock. However, upgrading from a read lock to the write lock is not possible.

  • Interruption of lock acquisition

The read lock and write lock both support interruption during lock acquisition.

  • Condition support

The write lock provides a Condition implementation that behaves in the same way, with respect to the write lock, as the Condition implementation provided by ReentrantLock#newCondition does for ReentrantLock. This Condition can, of course, only be used with the write lock.

The read lock does not support a Condition and readLock().newCondition() throws UnsupportedOperationException.

  • Instrumentation

This class supports methods to determine whether locks are held or contended. These methods are designed for monitoring system state, not for synchronization control.

Serialization of this class behaves in the same way as built-in locks: a deserialized lock is in the unlocked state, regardless of its state when serialized.

Sample usages. Here is a code sketch showing how to perform lock downgrading after updating a cache (exception handling is particularly tricky when handling multiple locks in a non-nested fashion):

class CachedData // Downgrade by acquiring read lock before releasing write lock 
rwl.readLock().lock(); 
} finally  
rwl.writeLock().unlock(); // Unlock write, still hold read 
} 
} 
try  
use(data); 
} finally  
rwl.readLock().unlock(); 
} 
} 
}}

ReentrantReadWriteLocks can be used to improve concurrency in some uses of some kinds of Collections. This is typically worthwhile only when the collections are expected to be large, accessed by more reader threads than writer threads, and entail operations with overhead that outweighs synchronization overhead. For example, here is a class using a TreeMap that is expected to be large and concurrently accessed.

class RWDictionary try { return m.get(key); } 
finally { r.unlock(); } 
} 
public String[] allKeys()  
r.lock(); 
try { return m.keySet().toArray(); } 
finally { r.unlock(); } 
} 
public Data put(String key, Data value)  
w.lock(); 
try { return m.put(key, value); } 
finally { w.unlock(); } 
} 
public void clear()  
w.lock(); 
try { m.clear(); } 
finally { w.unlock(); } 
} 
}}

Implementation Notes

This lock supports a maximum of 65535 recursive write locks and 65535 read locks. Attempts to exceed these limits result in Error throws from locking methods.
[中]ReadWriteLock的一种实现,支持与ReentrantLock类似的语义。
此类具有以下属性:
*收购令
此类不会对锁访问强制执行读写器首选项排序。不过,它确实支持可选的“公平”策略。非公平模式(默认)当构造为非公平(默认)时,读写锁的输入顺序未指定,受可重入性约束的约束。持续争用的非空锁可能会无限期地延迟一个或多个读写器线程,但通常比公平锁具有更高的吞吐量。
公平模式当被构造为公平时,线程使用近似到达顺序策略来竞争条目。释放当前持有的锁时,将为等待时间最长的单个写入线程分配写锁,或者如果有一组读线程比所有等待的写入线程等待时间更长,则将为该组分配读锁。
尝试获取公平读取锁(非可重入)的线程将在写入锁被持有或存在等待写入线程时阻塞。在当前等待的最旧写入线程获取并释放写锁之前,该线程不会获取读锁。当然,如果等待的写入程序放弃了等待,将一个或多个读线程作为队列中最长的等待程序,而写锁处于空闲状态,那么这些读卡器将被分配读锁。
试图获取公平写锁(非可重入)的线程将阻塞,除非读锁和写锁都是空闲的(这意味着没有等待的线程)。(请注意,非阻塞ReadLock#tryLock()和WriteLock#tryLock()方法不支持此公平设置,如果可能,将立即获取锁,而不考虑等待线程。)
*再入
该锁允许读写器以可重入锁的方式重新获取读或写锁。在释放写入线程持有的所有写入锁之前,不允许使用非可重入读卡器。
此外,写入程序可以获取读锁,但反之亦然。在其他应用程序中,当在调用或回调在读锁下执行读取的方法时持有写锁时,可重入性非常有用。如果读卡器试图获取写锁,它将永远不会成功。
*船闸降级
可重入性还允许从写锁降级为读锁,方法是先获取写锁,然后获取读锁,然后释放写锁。但是,不可能从读锁升级到写锁。
*锁获取中断
读锁和写锁都支持在锁获取期间中断。
*条件支持
写锁提供的条件实现与写锁的行为方式相同,就像ReentrantLock#newCondition为ReentrantLock提供的条件实现一样。当然,这种情况只能与写锁一起使用。
读锁不支持条件和读锁()。newCondition()抛出UnsupportedOperationException。
*仪器仪表
这个类支持确定锁是被持有还是被争用的方法。这些方法是为监控系统状态而设计的,而不是为同步控制而设计的。
此类的序列化与内置锁的行为相同:反序列化的锁处于解锁状态,而不管序列化时的状态如何。
示例用法。下面是一个代码草图,展示了如何在更新缓存后执行锁降级(当以非嵌套方式处理多个锁时,异常处理尤其棘手):

class CachedData // Downgrade by acquiring read lock before releasing write lock 
rwl.readLock().lock(); 
} finally  
rwl.writeLock().unlock(); // Unlock write, still hold read 
} 
} 
try  
use(data); 
} finally  
rwl.readLock().unlock(); 
} 
} 
}}

在某些类型的集合的某些使用中,可以使用ReentrantReadWriteLocks来提高并发性。只有当集合预计很大,读线程比写线程多,并且需要的操作开销超过同步开销时,这通常才有价值。例如,下面是一个使用树映射的类,该树映射应该是大型的,并且可以并发访问

class RWDictionary try { return m.get(key); } 
finally { r.unlock(); } 
} 
public String[] allKeys()  
r.lock(); 
try { return m.keySet().toArray(); } 
finally { r.unlock(); } 
} 
public Data put(String key, Data value)  
w.lock(); 
try { return m.put(key, value); } 
finally { w.unlock(); } 
} 
public void clear()  
w.lock(); 
try { m.clear(); } 
finally { w.unlock(); } 
} 
}}

####实施说明
此锁最多支持65535个递归写锁和65535个读锁。试图超过这些限制会导致锁定方法抛出错误。

代码示例

代码示例来源:origin: apache/ignite

/**
 * Release table lock.
 *
 * @param exclusive Exclusive flag.
 */
private void unlock(boolean exclusive) {
  Lock l = exclusive ? lock.writeLock() : lock.readLock();
  l.unlock();
}

代码示例来源:origin: apache/hive

private ReentrantReadWriteLock getDagLock(QueryIdentifier queryIdentifier) {
 lock.lock();
 try {
  ReentrantReadWriteLock dagLock = dagSpecificLocks.get(queryIdentifier);
  if (dagLock == null) {
   dagLock = new ReentrantReadWriteLock();
   dagSpecificLocks.put(queryIdentifier, dagLock);
  }
  return dagLock;
 } finally {
  lock.unlock();
 }
}

代码示例来源:origin: apache/ignite

/**
 * Queries if the write lock is held by the current thread.
 *
 * @return {@code true} if the current thread holds the write lock and
 *         {@code false} otherwise
 */
public boolean isWriteLockedByCurrentThread() {
  return locks[locks.length - 1].isWriteLockedByCurrentThread();
}

代码示例来源:origin: apache/ignite

/** {@inheritDoc} */
@Override public boolean holdsLock() {
  return lock.isWriteLockedByCurrentThread() || lock.getReadHoldCount() > 0;
}

代码示例来源:origin: apache/hbase

/**
 * Closes the lock. This needs to be called in the finally block corresponding
 * to the try block of #startRegionOperation
 */
private void closeBulkRegionOperation(){
 if (lock.writeLock().isHeldByCurrentThread()) lock.writeLock().unlock();
 else lock.readLock().unlock();
}

代码示例来源:origin: spotbugs/spotbugs

int foo() {
  ReadWriteLock myLock = new ReentrantReadWriteLock();
  myLock.writeLock().lock();
  int a = 6;
  int b = 9;
  int wrongAnswer = a * b;
  int rightAnswer = 42;
  myLock.writeLock().unlock();
  return wrongAnswer + rightAnswer;
}

代码示例来源:origin: oracle/opengrok

/**
 * Write the current configuration to a file
 *
 * @param file the file to write the configuration into
 * @throws IOException if an error occurs
 */
public void writeConfiguration(File file) throws IOException {
  Lock readLock = configLock.readLock();
  try {
    readLock.lock();
    configuration.write(file);
  } finally {
    readLock.unlock();
  }
}

代码示例来源:origin: oracle/opengrok

/**
 * Add repositories to the list.
 * @param repositories list of repositories
 */
public void addRepositories(List<RepositoryInfo> repositories) {
  Lock writeLock = configLock.writeLock();
  try {
    writeLock.lock();
    configuration.addRepositories(repositories);
  } finally {
    writeLock.unlock();
  }
}

代码示例来源:origin: pentaho/pentaho-kettle

int nrOutput = succeedingSteps.size();
inputRowSetsLock.writeLock().lock();
outputRowSetsLock.writeLock().lock();
try {
 inputRowSets = new ArrayList<>();
 inputRowSetsLock.writeLock().unlock();
 outputRowSetsLock.writeLock().unlock();

代码示例来源:origin: ReactiveX/RxJava

/**
 * Constructs an empty BehaviorSubject.
 * @since 2.0
 */
@SuppressWarnings("unchecked")
BehaviorSubject() {
  this.lock = new ReentrantReadWriteLock();
  this.readLock = lock.readLock();
  this.writeLock = lock.writeLock();
  this.subscribers = new AtomicReference<BehaviorDisposable<T>[]>(EMPTY);
  this.value = new AtomicReference<Object>();
  this.terminalEvent = new AtomicReference<Throwable>();
}

代码示例来源:origin: apache/ignite

/**
 *
 */
@Test
public void testNotOwnedLockRelease() {
  ReadWriteLock lock = new ReentrantReadWriteLock();
  lock.readLock().unlock();
}

代码示例来源:origin: spotbugs/spotbugs

public static void main(String args[]) throws Exception {
    ReentrantLock lock1 = new ReentrantLock();
    ReadWriteLock rwLock = new ReentrantReadWriteLock();
    Lock lock2 = rwLock.readLock();
    Lock lock3 = rwLock.writeLock();
    rwLock.readLock();

    lock1.newCondition();
    lock2.newCondition();
    lock1.tryLock();
    lock2.tryLock();
    lock3.tryLock();

    synchronized (lock1) {
      System.out.println("Howdy");
    }
  }
}

代码示例来源:origin: alibaba/druid

public void clearWhiteList() {
  lock.writeLock().lock();
  try {
    if (whiteList != null) {
      whiteList = null;
    }
  } finally {
    lock.writeLock().unlock();
  }
}

代码示例来源:origin: alibaba/druid

public JdbcSqlStat getSqlStat(String sql) {
  lock.readLock().lock();
  try {
    return sqlStatMap.get(sql);
  } finally {
    lock.readLock().unlock();
  }
}

代码示例来源:origin: Alluxio/alluxio

/**
  * Tests {@link LockResource} with {@link ReentrantReadWriteLock}.
  */
 @Test
 public void reentrantReadWriteLock() {
  ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

  try (LockResource r1 = new LockResource(lock.readLock())) {
   try (LockResource r2 = new LockResource(lock.readLock())) {
    assertEquals(lock.getReadHoldCount(), 2);
    assertTrue(lock.readLock().tryLock());
    lock.readLock().unlock();
   }
  }
  assertEquals(lock.getReadHoldCount(), 0);

  try (LockResource r1 = new LockResource(lock.writeLock())) {
   try (LockResource r2 = new LockResource(lock.readLock())) {
    assertTrue(lock.isWriteLockedByCurrentThread());
    assertEquals(lock.getReadHoldCount(), 1);
   }
  }
  assertFalse(lock.isWriteLockedByCurrentThread());
  assertEquals(lock.getReadHoldCount(), 0);

  try (LockResource r = new LockResource(lock.readLock())) {
   assertFalse(lock.writeLock().tryLock());
  }
 }
}

代码示例来源:origin: google/guava

@Override
 public ReadWriteLock get() {
  return new ReentrantReadWriteLock();
 }
};

代码示例来源:origin: prestodb/presto

private void supplyLookupSources()
  checkState(!lock.isWriteLockedByCurrentThread());
  lock.writeLock().lock();
  try {
    checkState(partitionsSet == partitions.length, "Not all set yet");
    lock.writeLock().unlock();

代码示例来源:origin: stackoverflow.com

import java.util.*;
import java.util.concurrent.locks.*;

public class UpgradeTest {

  public static void main(String[] args) 
  {   
    System.out.println("read to write test");
    ReadWriteLock lock = new ReentrantReadWriteLock();

    lock.readLock().lock(); // get our own read lock
    lock.writeLock().lock(); // upgrade to write lock
    System.out.println("passed");
  }

}

代码示例来源:origin: fengjiachun/Jupiter

@Override
public Collection<RegisterMeta> lookup(RegisterMeta.ServiceMeta serviceMeta) {
  RegisterValue value = registries.get(serviceMeta);
  if (value == null) {
    return Collections.emptyList();
  }
  final Lock readLock = value.lock.readLock();
  readLock.lock();
  try {
    return Lists.newArrayList(value.metaSet);
  } finally {
    readLock.unlock();
  }
}

代码示例来源:origin: ReactiveX/RxJava

/**
 * Constructs an empty BehaviorProcessor.
 * @since 2.0
 */
@SuppressWarnings("unchecked")
BehaviorProcessor() {
  this.value = new AtomicReference<Object>();
  this.lock = new ReentrantReadWriteLock();
  this.readLock = lock.readLock();
  this.writeLock = lock.writeLock();
  this.subscribers = new AtomicReference<BehaviorSubscription<T>[]>(EMPTY);
  this.terminalEvent = new AtomicReference<Throwable>();
}

相关文章