当前位置:   article > 正文

深入学习java源码之ReadWriteLock.readLock()与ReadWriteLock.writeLock()_lock.readlock().lock();

lock.readlock().lock();

深入学习java源码之ReadWriteLock.readLock()与ReadWriteLock.writeLock()

假设你的程序中涉及到对一些共享资源的读和写操作,且写操作没有读操作那么频繁。在没有写操作的时候,两个线程同时读一个资源没有任何问题,所以应该允许多个线程能在同时读取共享资源。但是如果有一个线程想去写这些共享资源,就不应该再有其它线程对该资源进行读或写(译者注:也就是说:读-读能共存,读-写不能共存,写-写不能共存)。这就需要一个读/写锁来解决这个问题。

对于lock的读写锁,可以通过new ReentrantReadWriteLock()获取到一个读写锁。所谓读写锁,便是多线程之间读不互斥,读写互斥。读写锁是一种自旋锁,如果当前没有读者,也没有写者,那么写者可以立刻获得锁,否则它必须自旋在那里,直到没有任何写者或读者。如果当前没有写者,那么读者可以立即获得该读写锁,否则读者必须自旋在那里,直到写者释放该锁。

我们假设对写操作的请求比对读操作的请求更重要,就要提升写请求的优先级。此外,如果读操作发生的比较频繁,我们又没有提升写操作的优先级,那么就会产生“饥饿”现象。请求写操作的线程会一直阻塞,直到所有的读线程都从ReadWriteLock上解锁了。如果一直保证新线程的读操作权限,那么等待写操作的线程就会一直阻塞下去,结果就是发生“饥饿”。因此,只有当没有线程正在锁住ReadWriteLock进行写操作,且没有线程请求该锁准备执行写操作时,才能保证读操作继续。

两个线程在一起进行读操作

  1. public class Main {
  2. public static void main(String[] args) {
  3. private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
  4. final Main m = new Main();
  5. new Thread(){
  6. public void run() {
  7. m.read(Thread.currentThread());
  8. };
  9. }.start();
  10. new Thread(){
  11. public void run() {
  12. m.read(Thread.currentThread());
  13. };
  14. }.start();
  15. }
  16. public void read(Thread thread) {
  17. readWriteLock.readLock().lock();
  18. try {
  19. long startTime = System.currentTimeMillis();
  20. while(System.currentTimeMillis() - startTime <= 1) {
  21. System.out.println(thread.getName()+"线程在进行读操作");
  22. }
  23. System.out.println(thread.getName()+"线程完成读操作");
  24. } finally {
  25. readWriteLock.unlock();
  26. }
  27. }
  28. }

可以看到两个线程同时进行读操作,效率大大的提升了。但是要注意的是,如果一个线程获取了读锁,那么另外的线程想要获取写锁则需要等待释放;而如果一个线程已经获取了写锁,则另外的线程想获取读锁或写锁都需要等待写锁被释放。

 

当其它线程没有对共享资源进行读操作或者写操作时,某个线程就有可能获得该共享资源的写锁,进而对共享资源进行写操作。有多少线程请求了写锁以及以何种顺序请求写锁并不重要,除非你想保证写锁请求的公平性。

  1. public class Main {
  2. //静态内部类实现线程共享
  3. static class Example{
  4. //创建lock
  5. ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
  6. //读操作
  7. public void read(){
  8. //获取读锁并上锁
  9. lock.readLock().lock();
  10. try{
  11. System.out.println("读线程开始");
  12. Thread.sleep(1000);
  13. System.out.println("读线程结束");
  14. }catch (Exception e){
  15. e.printStackTrace();
  16. }finally{
  17. //解锁
  18. lock.readLock().unlock();
  19. }
  20. }
  21. //写操作
  22. public void write(){
  23. //获取写锁并上锁
  24. lock.writeLock().lock();
  25. try{
  26. System.out.println("写线程开始");
  27. Thread.sleep(1000);
  28. System.out.println("写线程结束");
  29. }catch (Exception e){
  30. e.printStackTrace();
  31. }finally {
  32. //解锁
  33. lock.writeLock().unlock();
  34. }
  35. }
  36. }
  37. public static void main(String[] args) {
  38. final Example example = new Example();
  39. new Thread(new Runnable() {
  40. @Override
  41. public void run() {
  42. while (true){
  43. example.read();
  44. example.write();
  45. }
  46. }
  47. }).start();
  48. new Thread(new Runnable() {
  49. @Override
  50. public void run() {
  51. while (true){
  52. example.read();
  53. example.write();
  54. }
  55. }
  56. }).start();
  57. }
  58. }

运行结果:

根据结果可以发现,多线程下ReentrantReadWriteLock可以多线程同时读,但写的话同一时刻只有一个线程执行。

 

读写锁的应用场景,我们可以利用读写锁可是实现一个多线程下数据缓存的功能,具体实现思路如下:

  1. class dataCatch{
  2. Object data; //缓存的数据
  3. public volatile Boolean isCatch = false; //是否有缓存
  4. ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); //生成读写锁
  5. public void process(){
  6. lock.readLock().lock(); //先加读锁,此时数据不会被修改
  7. //数据没有缓存
  8. if(!isCatch){
  9. lock.readLock().unlock(); //解读锁
  10. lock.writeLock().lock(); //加写锁,此时数据不会被读到
  11. /********
  12. *
  13. * 执行数据查询操作并赋值给data
  14. *
  15. ********/
  16. isCatch = true;
  17. lock.readLock().lock(); //先加读锁后解写锁
  18. lock.writeLock().lock();
  19. }
  20. /********
  21. *
  22. * 放回data数据给用户
  23. *
  24. ********/
  25. lock.readLock().unlock(); //解读锁
  26. }
  27. }

 

总结:

1.synchronized是Java的关键字,是内置特性,而Lock是一个接口,可以用它来实现同步。

2.synchronized同步的时候,其中一条线程用完会自动释放锁,而Lock需要手动释放,如果不手动释放,可能会造成死锁。

3.使用synchronized如果其中一个线程不释放锁,那么其他需要获取锁的线程会一直等待下去,知道使用完释放或者出现异常,而Lock可以使用可以响应中断的锁或者使用规定等待时间的锁

4.synchronized无法得知是否获取到锁,而Lcok可以做到。

5.用ReadWriteLock可以提高多个线程进行读操作的效率。

所以综上所述,在两种锁的选择上,当线程对于资源的竞争不激烈的时候,效率差不太多,但是当大量线程同时竞争的时候,Lock的性能会远高于synchronized。

 

java源码

A ReadWriteLock维护一对关联的locks ,一个用于只读操作,一个用于写入。 read lock可以由多个阅读器线程同时进行,只要没有作者。 write lock是独家的。

所有ReadWriteLock实现必须保证的存储器同步效应writeLock操作(如在指定Lock接口)也保持相对于所述相关联的readLock 。 也就是说,一个线程成功获取读锁定将会看到在之前发布的写锁定所做的所有更新。

读写锁允许访问共享数据时的并发性高于互斥锁所允许的并发性。 它利用了这样一个事实:一次只有一个线程( 写入线程)可以修改共享数据,在许多情况下,任何数量的线程都可以同时读取数据(因此读取器线程)。 从理论上讲,通过使用读写锁允许的并发性增加将导致性能改进超过使用互斥锁。 实际上,并发性的增加只能在多处理器上完全实现,然后只有在共享数据的访问模式是合适的时才可以。

读写锁是否会提高使用互斥锁的性能取决于数据被读取的频率与被修改的频率相比,读取和写入操作的持续时间以及数据的争用 - 即是,将尝试同时读取或写入数据的线程数。 例如,最初填充数据的集合,然后经常被修改的频繁搜索(例如某种目录)是使用读写锁的理想候选。 然而,如果更新变得频繁,那么数据的大部分时间将被专门锁定,并且并发性增加很少。 此外,如果读取操作太短,则读写锁定实现(其本身比互斥锁更复杂)的开销可以支配执行成本,特别是因为许多读写锁定实现仍将序列化所有线程通过小部分代码。 最终,只有剖析和测量将确定使用读写锁是否适合您的应用程序。

虽然读写锁的基本操作是直接的,但是执行必须做出许多策略决策,这可能会影响给定应用程序中读写锁定的有效性。 这些政策的例子包括:

在评估应用程序的给定实现的适用性时,应考虑所有这些问题。

  • 在写入器释放写入锁定时,确定在读取器和写入器都在等待时是否授予读取锁定或写入锁定。 作家偏好是常见的,因为写作预计会很短,很少见。 读者喜好不常见,因为如果读者经常和长期的预期,写作可能导致漫长的延迟。 公平的或“按顺序”的实现也是可能的。
  • 确定在读卡器处于活动状态并且写入器正在等待时请求读取锁定的读取器是否被授予读取锁定。 读者的偏好可以无限期地拖延作者,而对作者的偏好可以减少并发的潜力。
  • 确定锁是否可重入:一个具有写锁的线程是否可以重新获取? 持有写锁可以获取读锁吗? 读锁本身是否可重入?
  • 写入锁可以降级到读锁,而不允许插入写者? 读锁可以升级到写锁,优先于其他等待读者或作者吗?
Modifier and TypeMethod and Description
LockreadLock()

返回用于阅读的锁。

LockwriteLock()

返回用于写入的锁。

  1. package java.util.concurrent.locks;
  2. public interface ReadWriteLock {
  3. Lock readLock();
  4. Lock writeLock();
  5. }

 

Modifier and TypeMethod and Description
protected ThreadgetOwner()

返回当前拥有写锁的线程,如果不拥有,则返回 null

protected Collection<Thread>getQueuedReaderThreads()

返回一个包含可能正在等待获取读取锁的线程的集合。

protected Collection<Thread>getQueuedThreads()

返回一个包含可能正在等待获取读取或写入锁定的线程的集合。

protected Collection<Thread>getQueuedWriterThreads()

返回一个包含可能正在等待获取写入锁的线程的集合。

intgetQueueLength()

返回等待获取读取或写入锁定的线程数的估计。

intgetReadHoldCount()

查询当前线程对此锁的可重入读取保留数。

intgetReadLockCount()

查询为此锁持有的读取锁的数量。

protected Collection<Thread>getWaitingThreads(Condition condition)

返回包含可能在与写锁相关联的给定条件下等待的线程的集合。

intgetWaitQueueLength(Condition condition)

返回与写入锁相关联的给定条件等待的线程数的估计。

intgetWriteHoldCount()

查询当前线程对此锁的可重入写入数量。

booleanhasQueuedThread(Thread thread)

查询给定线程是否等待获取读取或写入锁定。

booleanhasQueuedThreads()

查询是否有任何线程正在等待获取读取或写入锁定。

booleanhasWaiters(Condition condition)

查询任何线程是否等待与写锁相关联的给定条件。

booleanisFair()

如果此锁的公平设置为true,则返回 true

booleanisWriteLocked()

查询写锁是否由任何线程持有。

booleanisWriteLockedByCurrentThread()

查询写锁是否由当前线程持有。

ReentrantReadWriteLock.ReadLockreadLock()

返回用于阅读的锁。

StringtoString()

返回一个标识此锁的字符串以及其锁定状态。

ReentrantReadWriteLock.WriteLockwriteLock()

返回用于写入的锁。

  1. package java.util.concurrent.locks;
  2. import java.util.concurrent.TimeUnit;
  3. import java.util.Collection;
  4. public class ReentrantReadWriteLock
  5. implements ReadWriteLock, java.io.Serializable {
  6. private static final long serialVersionUID = -6992448646407690164L;
  7. /** Inner class providing readlock */
  8. private final ReentrantReadWriteLock.ReadLock readerLock;
  9. /** Inner class providing writelock */
  10. private final ReentrantReadWriteLock.WriteLock writerLock;
  11. /** Performs all synchronization mechanics */
  12. final Sync sync;
  13. public ReentrantReadWriteLock() {
  14. this(false);
  15. }
  16. public ReentrantReadWriteLock(boolean fair) {
  17. sync = fair ? new FairSync() : new NonfairSync();
  18. readerLock = new ReadLock(this);
  19. writerLock = new WriteLock(this);
  20. }
  21. public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
  22. public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; }
  23. abstract static class Sync extends AbstractQueuedSynchronizer {
  24. private static final long serialVersionUID = 6317671515068378041L;
  25. static final int SHARED_SHIFT = 16;
  26. static final int SHARED_UNIT = (1 << SHARED_SHIFT);
  27. static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1;
  28. static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
  29. /** Returns the number of shared holds represented in count */
  30. static int sharedCount(int c) { return c >>> SHARED_SHIFT; }
  31. /** Returns the number of exclusive holds represented in count */
  32. static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
  33. static final class HoldCounter {
  34. int count = 0;
  35. // Use id, not reference, to avoid garbage retention
  36. final long tid = getThreadId(Thread.currentThread());
  37. }
  38. static final class ThreadLocalHoldCounter
  39. extends ThreadLocal<HoldCounter> {
  40. public HoldCounter initialValue() {
  41. return new HoldCounter();
  42. }
  43. }
  44. private transient ThreadLocalHoldCounter readHolds;
  45. private transient HoldCounter cachedHoldCounter;
  46. private transient Thread firstReader = null;
  47. private transient int firstReaderHoldCount;
  48. Sync() {
  49. readHolds = new ThreadLocalHoldCounter();
  50. setState(getState()); // ensures visibility of readHolds
  51. }
  52. abstract boolean readerShouldBlock();
  53. abstract boolean writerShouldBlock();
  54. protected final boolean tryRelease(int releases) {
  55. if (!isHeldExclusively())
  56. throw new IllegalMonitorStateException();
  57. int nextc = getState() - releases;
  58. boolean free = exclusiveCount(nextc) == 0;
  59. if (free)
  60. setExclusiveOwnerThread(null);
  61. setState(nextc);
  62. return free;
  63. }
  64. protected final boolean tryAcquire(int acquires) {
  65. Thread current = Thread.currentThread();
  66. int c = getState();
  67. int w = exclusiveCount(c);
  68. if (c != 0) {
  69. // (Note: if c != 0 and w == 0 then shared count != 0)
  70. if (w == 0 || current != getExclusiveOwnerThread())
  71. return false;
  72. if (w + exclusiveCount(acquires) > MAX_COUNT)
  73. throw new Error("Maximum lock count exceeded");
  74. // Reentrant acquire
  75. setState(c + acquires);
  76. return true;
  77. }
  78. if (writerShouldBlock() ||
  79. !compareAndSetState(c, c + acquires))
  80. return false;
  81. setExclusiveOwnerThread(current);
  82. return true;
  83. }
  84. protected final boolean tryReleaseShared(int unused) {
  85. Thread current = Thread.currentThread();
  86. if (firstReader == current) {
  87. // assert firstReaderHoldCount > 0;
  88. if (firstReaderHoldCount == 1)
  89. firstReader = null;
  90. else
  91. firstReaderHoldCount--;
  92. } else {
  93. HoldCounter rh = cachedHoldCounter;
  94. if (rh == null || rh.tid != getThreadId(current))
  95. rh = readHolds.get();
  96. int count = rh.count;
  97. if (count <= 1) {
  98. readHolds.remove();
  99. if (count <= 0)
  100. throw unmatchedUnlockException();
  101. }
  102. --rh.count;
  103. }
  104. for (;;) {
  105. int c = getState();
  106. int nextc = c - SHARED_UNIT;
  107. if (compareAndSetState(c, nextc))
  108. // Releasing the read lock has no effect on readers,
  109. // but it may allow waiting writers to proceed if
  110. // both read and write locks are now free.
  111. return nextc == 0;
  112. }
  113. }
  114. private IllegalMonitorStateException unmatchedUnlockException() {
  115. return new IllegalMonitorStateException(
  116. "attempt to unlock read lock, not locked by current thread");
  117. }
  118. protected final int tryAcquireShared(int unused) {
  119. Thread current = Thread.currentThread();
  120. int c = getState();
  121. if (exclusiveCount(c) != 0 &&
  122. getExclusiveOwnerThread() != current)
  123. return -1;
  124. int r = sharedCount(c);
  125. if (!readerShouldBlock() &&
  126. r < MAX_COUNT &&
  127. compareAndSetState(c, c + SHARED_UNIT)) {
  128. if (r == 0) {
  129. firstReader = current;
  130. firstReaderHoldCount = 1;
  131. } else if (firstReader == current) {
  132. firstReaderHoldCount++;
  133. } else {
  134. HoldCounter rh = cachedHoldCounter;
  135. if (rh == null || rh.tid != getThreadId(current))
  136. cachedHoldCounter = rh = readHolds.get();
  137. else if (rh.count == 0)
  138. readHolds.set(rh);
  139. rh.count++;
  140. }
  141. return 1;
  142. }
  143. return fullTryAcquireShared(current);
  144. }
  145. final int fullTryAcquireShared(Thread current) {
  146. HoldCounter rh = null;
  147. for (;;) {
  148. int c = getState();
  149. if (exclusiveCount(c) != 0) {
  150. if (getExclusiveOwnerThread() != current)
  151. return -1;
  152. // else we hold the exclusive lock; blocking here
  153. // would cause deadlock.
  154. } else if (readerShouldBlock()) {
  155. // Make sure we're not acquiring read lock reentrantly
  156. if (firstReader == current) {
  157. // assert firstReaderHoldCount > 0;
  158. } else {
  159. if (rh == null) {
  160. rh = cachedHoldCounter;
  161. if (rh == null || rh.tid != getThreadId(current)) {
  162. rh = readHolds.get();
  163. if (rh.count == 0)
  164. readHolds.remove();
  165. }
  166. }
  167. if (rh.count == 0)
  168. return -1;
  169. }
  170. }
  171. if (sharedCount(c) == MAX_COUNT)
  172. throw new Error("Maximum lock count exceeded");
  173. if (compareAndSetState(c, c + SHARED_UNIT)) {
  174. if (sharedCount(c) == 0) {
  175. firstReader = current;
  176. firstReaderHoldCount = 1;
  177. } else if (firstReader == current) {
  178. firstReaderHoldCount++;
  179. } else {
  180. if (rh == null)
  181. rh = cachedHoldCounter;
  182. if (rh == null || rh.tid != getThreadId(current))
  183. rh = readHolds.get();
  184. else if (rh.count == 0)
  185. readHolds.set(rh);
  186. rh.count++;
  187. cachedHoldCounter = rh; // cache for release
  188. }
  189. return 1;
  190. }
  191. }
  192. }
  193. final boolean tryWriteLock() {
  194. Thread current = Thread.currentThread();
  195. int c = getState();
  196. if (c != 0) {
  197. int w = exclusiveCount(c);
  198. if (w == 0 || current != getExclusiveOwnerThread())
  199. return false;
  200. if (w == MAX_COUNT)
  201. throw new Error("Maximum lock count exceeded");
  202. }
  203. if (!compareAndSetState(c, c + 1))
  204. return false;
  205. setExclusiveOwnerThread(current);
  206. return true;
  207. }
  208. final boolean tryReadLock() {
  209. Thread current = Thread.currentThread();
  210. for (;;) {
  211. int c = getState();
  212. if (exclusiveCount(c) != 0 &&
  213. getExclusiveOwnerThread() != current)
  214. return false;
  215. int r = sharedCount(c);
  216. if (r == MAX_COUNT)
  217. throw new Error("Maximum lock count exceeded");
  218. if (compareAndSetState(c, c + SHARED_UNIT)) {
  219. if (r == 0) {
  220. firstReader = current;
  221. firstReaderHoldCount = 1;
  222. } else if (firstReader == current) {
  223. firstReaderHoldCount++;
  224. } else {
  225. HoldCounter rh = cachedHoldCounter;
  226. if (rh == null || rh.tid != getThreadId(current))
  227. cachedHoldCounter = rh = readHolds.get();
  228. else if (rh.count == 0)
  229. readHolds.set(rh);
  230. rh.count++;
  231. }
  232. return true;
  233. }
  234. }
  235. }
  236. protected final boolean isHeldExclusively() {
  237. // While we must in general read state before owner,
  238. // we don't need to do so to check if current thread is owner
  239. return getExclusiveOwnerThread() == Thread.currentThread();
  240. }
  241. // Methods relayed to outer class
  242. final ConditionObject newCondition() {
  243. return new ConditionObject();
  244. }
  245. final Thread getOwner() {
  246. // Must read state before owner to ensure memory consistency
  247. return ((exclusiveCount(getState()) == 0) ?
  248. null :
  249. getExclusiveOwnerThread());
  250. }
  251. final int getReadLockCount() {
  252. return sharedCount(getState());
  253. }
  254. final boolean isWriteLocked() {
  255. return exclusiveCount(getState()) != 0;
  256. }
  257. final int getWriteHoldCount() {
  258. return isHeldExclusively() ? exclusiveCount(getState()) : 0;
  259. }
  260. final int getReadHoldCount() {
  261. if (getReadLockCount() == 0)
  262. return 0;
  263. Thread current = Thread.currentThread();
  264. if (firstReader == current)
  265. return firstReaderHoldCount;
  266. HoldCounter rh = cachedHoldCounter;
  267. if (rh != null && rh.tid == getThreadId(current))
  268. return rh.count;
  269. int count = readHolds.get().count;
  270. if (count == 0) readHolds.remove();
  271. return count;
  272. }
  273. private void readObject(java.io.ObjectInputStream s)
  274. throws java.io.IOException, ClassNotFoundException {
  275. s.defaultReadObject();
  276. readHolds = new ThreadLocalHoldCounter();
  277. setState(0); // reset to unlocked state
  278. }
  279. final int getCount() { return getState(); }
  280. }
  281. static final class NonfairSync extends Sync {
  282. private static final long serialVersionUID = -8159625535654395037L;
  283. final boolean writerShouldBlock() {
  284. return false; // writers can always barge
  285. }
  286. final boolean readerShouldBlock() {
  287. return apparentlyFirstQueuedIsExclusive();
  288. }
  289. }
  290. static final class FairSync extends Sync {
  291. private static final long serialVersionUID = -2274990926593161451L;
  292. final boolean writerShouldBlock() {
  293. return hasQueuedPredecessors();
  294. }
  295. final boolean readerShouldBlock() {
  296. return hasQueuedPredecessors();
  297. }
  298. }
  299. public static class ReadLock implements Lock, java.io.Serializable {
  300. private static final long serialVersionUID = -5992448646407690164L;
  301. private final Sync sync;
  302. protected ReadLock(ReentrantReadWriteLock lock) {
  303. sync = lock.sync;
  304. }
  305. public void lock() {
  306. sync.acquireShared(1);
  307. }
  308. public void lockInterruptibly() throws InterruptedException {
  309. sync.acquireSharedInterruptibly(1);
  310. }
  311. public boolean tryLock() {
  312. return sync.tryReadLock();
  313. }
  314. public boolean tryLock(long timeout, TimeUnit unit)
  315. throws InterruptedException {
  316. return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
  317. }
  318. public void unlock() {
  319. sync.releaseShared(1);
  320. }
  321. public Condition newCondition() {
  322. throw new UnsupportedOperationException();
  323. }
  324. public String toString() {
  325. int r = sync.getReadLockCount();
  326. return super.toString() +
  327. "[Read locks = " + r + "]";
  328. }
  329. }
  330. public static class WriteLock implements Lock, java.io.Serializable {
  331. private static final long serialVersionUID = -4992448646407690164L;
  332. private final Sync sync;
  333. protected WriteLock(ReentrantReadWriteLock lock) {
  334. sync = lock.sync;
  335. }
  336. public void lock() {
  337. sync.acquire(1);
  338. }
  339. public void lockInterruptibly() throws InterruptedException {
  340. sync.acquireInterruptibly(1);
  341. }
  342. public boolean tryLock( ) {
  343. return sync.tryWriteLock();
  344. }
  345. public boolean tryLock(long timeout, TimeUnit unit)
  346. throws InterruptedException {
  347. return sync.tryAcquireNanos(1, unit.toNanos(timeout));
  348. }
  349. public void unlock() {
  350. sync.release(1);
  351. }
  352. public Condition newCondition() {
  353. return sync.newCondition();
  354. }
  355. public String toString() {
  356. Thread o = sync.getOwner();
  357. return super.toString() + ((o == null) ?
  358. "[Unlocked]" :
  359. "[Locked by thread " + o.getName() + "]");
  360. }
  361. public boolean isHeldByCurrentThread() {
  362. return sync.isHeldExclusively();
  363. }
  364. public int getHoldCount() {
  365. return sync.getWriteHoldCount();
  366. }
  367. }
  368. // Instrumentation and status
  369. public final boolean isFair() {
  370. return sync instanceof FairSync;
  371. }
  372. protected Thread getOwner() {
  373. return sync.getOwner();
  374. }
  375. public int getReadLockCount() {
  376. return sync.getReadLockCount();
  377. }
  378. public boolean isWriteLocked() {
  379. return sync.isWriteLocked();
  380. }
  381. public boolean isWriteLockedByCurrentThread() {
  382. return sync.isHeldExclusively();
  383. }
  384. public int getWriteHoldCount() {
  385. return sync.getWriteHoldCount();
  386. }
  387. public int getReadHoldCount() {
  388. return sync.getReadHoldCount();
  389. }
  390. protected Collection<Thread> getQueuedWriterThreads() {
  391. return sync.getExclusiveQueuedThreads();
  392. }
  393. protected Collection<Thread> getQueuedReaderThreads() {
  394. return sync.getSharedQueuedThreads();
  395. }
  396. public final boolean hasQueuedThreads() {
  397. return sync.hasQueuedThreads();
  398. }
  399. public final boolean hasQueuedThread(Thread thread) {
  400. return sync.isQueued(thread);
  401. }
  402. public final int getQueueLength() {
  403. return sync.getQueueLength();
  404. }
  405. protected Collection<Thread> getQueuedThreads() {
  406. return sync.getQueuedThreads();
  407. }
  408. public boolean hasWaiters(Condition condition) {
  409. if (condition == null)
  410. throw new NullPointerException();
  411. if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
  412. throw new IllegalArgumentException("not owner");
  413. return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
  414. }
  415. public int getWaitQueueLength(Condition condition) {
  416. if (condition == null)
  417. throw new NullPointerException();
  418. if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
  419. throw new IllegalArgumentException("not owner");
  420. return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
  421. }
  422. protected Collection<Thread> getWaitingThreads(Condition condition) {
  423. if (condition == null)
  424. throw new NullPointerException();
  425. if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
  426. throw new IllegalArgumentException("not owner");
  427. return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
  428. }
  429. public String toString() {
  430. int c = sync.getCount();
  431. int w = Sync.exclusiveCount(c);
  432. int r = Sync.sharedCount(c);
  433. return super.toString() +
  434. "[Write locks = " + w + ", Read locks = " + r + "]";
  435. }
  436. static final long getThreadId(Thread thread) {
  437. return UNSAFE.getLongVolatile(thread, TID_OFFSET);
  438. }
  439. // Unsafe mechanics
  440. private static final sun.misc.Unsafe UNSAFE;
  441. private static final long TID_OFFSET;
  442. static {
  443. try {
  444. UNSAFE = sun.misc.Unsafe.getUnsafe();
  445. Class<?> tk = Thread.class;
  446. TID_OFFSET = UNSAFE.objectFieldOffset
  447. (tk.getDeclaredField("tid"));
  448. } catch (Exception e) {
  449. throw new Error(e);
  450. }
  451. }
  452. }

 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/910228
推荐阅读
相关标签
  

闽ICP备14008679号