reentrantlock

ReentrantLock源码解析

柔情痞子 提交于 2019-12-23 02:20:44
前面刚学习了AQS的基本原理,主要通过两个队列实现功能(同步队列+等待队列,前者是双向链表,实现加锁和解锁,后者是单向链表,用做同步协作,阻塞、唤醒),正好可以趁热打铁,了解一下ReentrantLock的源码,有了AQS的基础,阅读ReentrantLock的源码是非常简单的,如果没有了解AQS原理的同学,可以参考: AbstractQueuedSynchronizer源码(上)–排他锁 AbstractQueuedSynchronizer源码(下)–共享锁和Condition条件队列 我们都知道ReentrantLock的底层就是通过AQS实现,和Synchronized一样都是可重入锁,同时也是排他锁,所以ReentrantLock只能一个线程获取锁,但是线程可以获取当前资源的多重锁,对应锁数量+1,每次释放-1,直到等于0,才可以被其他线程竞争获取锁,有点引用计数法的意思。 类定义: public class ReentrantLock implements Lock , java . io . Serializable { private final Sync sync ; //默认构造函数,得到的事非公平锁 public ReentrantLock ( ) { sync = new NonfairSync ( ) ; } //支持传入fair参数,得到是否公平锁

ReentrantLock Condition

荒凉一梦 提交于 2019-12-23 00:40:25
package com.company.bingfa; import org.omg.PortableServer.THREAD_POLICY_ID; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; class MyService{ ReentrantLock reentrantLock = new ReentrantLock(); Condition conditionA = reentrantLock.newCondition(); Condition conditionB = reentrantLock.newCondition(); public void waitA(){ try{ reentrantLock.lock(); System.out.println("start A"); conditionA.await(); System.out.println("finish A"); } catch (InterruptedException e) { e.printStackTrace(); } finally { reentrantLock.unlock(); } } public void waitB(){ try{

Java多线程 ReentrantLock、Condition 实现生产者、消费者协作模式

核能气质少年 提交于 2019-12-22 03:37:33
一、锁接口 Lock,ReadWriteLock:   1、Lock,实现类有ReentractLock、WriteLock、ReadLock;   2、ReadWriteLock,主要实现类是ReentrantReadWriteLock,有两个方法 writeLock()、readLock() ,返回值是 WriteLock,ReadLock,这两类继承与Lock接口;   3、常用方法:     lock() / unlock():获取/释放锁,lock()会阻塞直到成功     lockInterruptibly():与lock() 不同的是它可以响应中断,如果被其他线程中断了,则抛出InterruptedException     tryLock() / tyrLock(long time, TimeUnit unit):只是尝试获取锁,立即返回,返回值为 boolean。无参数不阻塞,有参数会根据设置的时间阻塞等待,如果发生中断抛出InterruptedException     newCondition:新建一个条件,一个lock可以关联多个条件 二、对比 ReentractLock 和 synchornized:     相比synchronized,ReentractLock可以实现与synchronized 相同的语义,而且支持以非阻塞方法获取锁,可以响应中断

ReentrantLock代码剖析之ReentrantLock.unlock

我与影子孤独终老i 提交于 2019-12-21 03:41:30
下面来看ReentrantLock.unlock,尝试在当前锁的锁定计数即state值上减1,而lock每次把锁定计数加1,这也是为什么lock和unlock必须成对出现,否则锁定计数就不能正常恢复到0,其它线程就不能尝试获取锁 ReentrantLock.unlock() /** * Attempts to release this lock. * * <p>If the current thread is the holder of this lock then the hold * count is decremented. If the hold count is now zero then the lock * is released. If the current thread is not the holder of this * lock then { @link IllegalMonitorStateException} is thrown. * * @throws IllegalMonitorStateException if the current thread does not * hold this lock */ public void unlock() { sync.release( 1 ); } AbstractQueuedsynchronizer

ReentrantLock 可重入锁

爱⌒轻易说出口 提交于 2019-12-20 21:09:00
ReentrantLock 可重入锁 ReentrantLock,可重入锁,是一种递归无阻塞的同步机制。它可以等同于synchronized的使用,但是ReentrantLock提供了比synchronized更强大、灵活的锁机制,可以减少死锁发生的概率。 公平锁与非公平锁 ReentrantLock还提供了公平锁也非公平锁的选择,构造方法接受一个可选的公平参数(默认非公平锁),当设置为true时,表示公平锁,否则为非公平锁。 public ReentrantLock(boolean fair) { sync = fair ? new FairSync() : new NonfairSync(); } 公平锁与非公平锁的区别在于公平锁的锁获取是有顺序的。但是公平锁的效率往往没有非公平锁的效率高,在许多线程访问的情况下,公平锁表现出较低的吞吐量。 ReentrantLock与synchronized的区别 与synchronized相比,ReentrantLock提供了更多,更加全面的功能,具备更强的扩展性。例如:时间锁等候,可中断锁等候,锁投票。 ReentrantLock还提供了条件Condition,对线程的等待、唤醒操作更加详细和灵活,所以在多个条件变量和高度竞争锁的地方,ReentrantLock更加适合(以后会阐述Condition)。

ReentrantLock doesn't work out

十年热恋 提交于 2019-12-20 04:48:39
问题 I can't figure out why the code doesn't work properly. The problem is that ReentrantLock doesn't lock methods invocation in ThreadClass.run() Resource-class which methods are assumed to be locked in ThreadClass public class ResourceClass { private int i; public void setIncrement() { i++; } public int getIncrement() { return i; } } Thread-class public class ThreadClass implements Runnable { private ResourceClass resource; private ReentrantLock reentrantLock = new ReentrantLock(); ThreadClass

Java ReentrantLock and Condition | producers finish work, consumer gets stuck

空扰寡人 提交于 2019-12-20 04:26:11
问题 General Information: Three reader-threads read randomly from a file in chunks where each chunk has an ID and they write to a normal ArrayList. A writer-thread writes to an outputfile as soon as a chunk with the needed ID is added to the list. For that reason I have written a BlockingChunkList which should synchronize the add() and getNextChunk() methods. It works for me with synchronized + notify + notifyAll in one case and with a synchronized list in another. I don't manage to do it when I

Java面试题300道

北战南征 提交于 2019-12-20 00:16:28
一、性能调优系列 1.Tomcat性能调优 JVM参数调优: -Xms<size> 表示JVM初始化堆的大小,一Xmx<size>表示JVM堆的最大值。这两个值的大小一般根据需要进行设置。当应用程序需要的内存超出堆的最大值时虚拟机就会提示内存溢出,并且导致应用服务崩溃。因此- -般建议堆的最大值设置为可用内存的最大值的80%。在catalina.bat中,设置JAVA _0PTS='-Xms256m-Xmx512m',表示初始化内存为256MB,可以使用的最大内存512MB。 2.JVM性能调优 Java类加载过程 Java类加载需要经历一下7个过程: 1.加载 加载是类加载的第一个过程,在这个阶段,将完成一下三件事情 (1)通过一个类的全限定名获取该类的二进制流。 (2)将该二进制流中的静态存储结构转化为方法去运行时数据结构。 (3)在内存中生成该类的Class对象,作为该类的数据访问入口。 2.验证 验证的目的是为了确保Class文件的字节流中的信息不回危害到虚拟机.在该阶段主要完成以下四钟验证: (1)文件格式验证:验证字节流是否符合Class文件的规范,如主次版本号是否在当前虚拟机范围内,常量池中的常量是否有不被支持的类型. (2)元数据验证:对字节码描述的信息进行语义分析,如这个类是否有父类,是否集成了不被继承的类等。 (3)字节码验证:是整个验证过程中最复杂的一个阶段

Java : ReentrantReadWriteLock with priority

一世执手 提交于 2019-12-19 02:54:28
问题 The following is the typical reader and writer pattern (a lot of reads and few writes) private ReadWriteLock lock = new ReentrantReadWriteLock(); private int value; public void writeValue(int newValue){ lock.writeLock().lock(); try{ this.value = newValue; } finally{ lock.writeLock().unlock(); } } public int readValue(){ lock.readLock().lock(); try{ return value; } finally{ lock.writeLock().unlock(); } } I am wondering that is it possible to have priority to writer and reader ? For example,

Java容器:Stack,Queue,PriorityQueue和BlockingQueue

血红的双手。 提交于 2019-12-18 10:02:47
Stack Queue PriorityQueue BlockingQueue ArrayBlockingQueue LinkedBlockingQueue PriorityBlockingQueue DelayQueue SynchronousQueue 参考文章 1. Stack Java中Stack类继承了Vector类,在其基础上实现了了栈的功能。由于是直接继承而非通过接口进行隐藏(如Queue虽然由LinkedList实现,但对其非队列接口进行了隐藏),Java的Stack拥有Vector的所有方法并且继承了其线程安全特性(所以也和Vector一样在性能上有所损耗)。 在List的基础上,Stack添加了以下方法: push:向栈中压入一个元素并返回该元素。 peek:获取栈顶元素,栈为空抛出异常。 pop:获取并弹出栈顶元素,栈为空抛出异常。 empty:同isEmpty()。 search:基于lastIndexOf()实现,返回搜索元素离栈顶的最近距离。 可见,Stack是一个古老的,并为了模拟栈的操作不惜重复实现同一函数的方法。当比较注重效率时,显然基于LinkedList或者ArrayList对栈重新实现,会有更好的效果。 2. Queue 从继承层次上看,Queue和List,Map,Set一样,是直接继承了Collections类的容器类,但是从其实现上看