当前位置:网站首页>Example of producer consumer code implemented by the destructor framework without lock
Example of producer consumer code implemented by the destructor framework without lock
2022-07-24 02:49:00 【march of Time】
( Excerpt from 《 actual combat Java High concurrency programming 》)
Disruptor Framework is made up of LMAX An efficient unlocked memory queue developed by the company . It implements a ring queue in a lock free way , It is very suitable for realizing the producer and consumer model , Such as the release of events and news . stay Disruptor in , Ingeniously used the ring queue (RingBuffer) To replace ordinary linear queues , This circular queue is internally implemented as a normal array . For a general queue , It's bound to provide queue synchronization head And the tail tail Two pointers , Used to get out and get in , This undoubtedly increases the complexity of thread collaboration . But if the queue is circular , You only need to provide a current location cursor, Using this pointer, you can enter the queue or exit the queue . Because of the circular queue , The total size of the queue must be specified in advance , Can't dynamically expand . To be able to quickly start from a sequence (sequence) Corresponding to the actual position of the array ( Every time there are elements in the team , The sequence adds 1),Disruptor It requires that we must set the size of the array to 2 Integer power of . This way sequence&(queueSize-1) You can immediately locate the actual element position index. This is better than the remainder (%) It's much faster .
Another advantage of this fixed size ring queue is that it can achieve complete memory reuse . During the operation of the system , There will be no new space to allocate or old space to recycle . therefore , It can greatly reduce the additional overhead of system allocation space and recycling space .
Code :
Data class :
public class PData {
private long value;
public void setValue(long value) {
this.value = value;
}
public long getValue() {
return value;
}
}
Data production factory :
public class PFactory implements EventFactory<PData> {
@Override
public PData newInstance() {
return new PData();
}
}
consumer :
public class Consumer implements WorkHandler<PData> {
@Override
public void onEvent(PData pData) throws Exception {
System.out.println(" Threads ID:"+Thread.currentThread().getId()+": Consumption data "+pData.getValue());
}
}
Producers and main functions :
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
/** * @author hzy * @date 2022-07-21 */
public class Producer {
private final RingBuffer<PData> ringBuffer;
public Producer(RingBuffer<PData> ringBuffer) {
this.ringBuffer = ringBuffer;
}
public void pushData(ByteBuffer buffer) {
long sequence = ringBuffer.next();
try{
PData data = ringBuffer.get(sequence);
data.setValue(buffer.getLong(0));
}catch(Exception e){
}
finally{
ringBuffer.publish(sequence);
}
}
public static void main(String[] args) throws InterruptedException {
Executor excutor = Executors.newCachedThreadPool();
EventFactory factory =new PFactory();
int bufferSize = 1024;
Disruptor<PData>disruptor = new Disruptor<PData>(factory,
bufferSize,
excutor,
ProducerType.MULTI,
new BlockingWaitStrategy());
disruptor.handleEventsWithWorkerPool(new Consumer(),
new Consumer(),
new Consumer(),
new Consumer());
disruptor.start();
RingBuffer<PData>ringBuffer = disruptor.getRingBuffer();
Producer producer = new Producer(ringBuffer);
ByteBuffer byteBuffer = java.nio.ByteBuffer.allocate(8);
for(long value = 0L;value < 10L;value++){
byteBuffer.putLong(0,value);
producer.pushData(byteBuffer);
Thread.sleep(10);
System.out.println("add a data"+value);
}
}
}
Running results :
边栏推荐
- O3DE 的Lumberyard 游戏引擎
- Reading notes: self cultivation of programmers - Chapter 3
- The solution of using non root user management in secure stand-alone database under general machine environment
- Jina AI and datawhale jointly launched a learning project!
- 攻防世界WEB练习区(weak_auth、simple_php、xff_referer)
- Ugui source code analysis - imaterialmodifier
- [interview: concurrent Article 21: multithreading: activeness] deadlock, livelock, hunger
- X Actual combat - Cloud Server
- AcWing 4498. 指针 (DFS)
- Unscramble the category and application principle of robot vision
猜你喜欢

云原生讲解【扩展篇】

软考---程序设计语言基础(上)

Skywalking distributed system application performance monitoring tool - upper

Unity timeline tutorial

22 -- range and of binary search tree

攻防世界WEB练习区(view_source、get_post、robots)

Chinese scientists have made new progress in high security quantum key distribution networks

ssm的求职招聘系统兼职应聘求职

To forge ahead on a new journey, the city chain science and technology carnival was grandly held in Xiamen

Honey, we are homeless now
随机推荐
Honey, we are homeless now
Mysql database, sorting and single line processing functions
开源量子开发框架 Cirq
记于2022.7.21
Ugui source code analysis - imaterialmodifier
Detailed vector
go IO操作-文件读
Recorded on July 21, 2022
compostion-api(setup中) watch使用细节
Mysql数据库,排序与单行处理函数篇
攻防世界WEB練習區(view_source、get_post、robots)
通用机环境下安全版单机数据库使用非root用户管理的解决方案
Make life full of happiness
攻防世界WEB练习区(weak_auth、simple_php、xff_referer)
TCP connection principle
Understand the low code implementation of microservices
Essential skills for programmers -- breakpoint debugging (idea version)
Nirvana rebirth! Byte Daniel recommends a large distributed manual, and the Phoenix architecture makes you become a God in fire
[datasets] - downloading some datasets of flyingthings3d optical flow
理解加载class到JVM的时机