Exchanger, Changing data between concurrent tasks
The Java concurrency API provides a synchronization utility that allows the interchange of data between two concurrent tasks. In more detail, the Exchanger class allows the definition of a synchronization point between two threads. When the two threads arrive to this point, they interchange a data structure so the data structure of the first thread goes to the second one and the data structure of the second thread goes to the first one.
This class may be very useful in a situation similar to the producer-consumer problem. This is a classic concurrent problem where you have a common buffer of data, one or more producers of data, and one or more consumers of data. As the Exchanger class only synchronizes two threads, you can use it if you have a producer-consumer problem with one producer and one consumer.
In this recipe, you will learn how to use the Exchanger class to solve the producer-consumer problem with one producer and one consumer.
1. First, let's begin by implementing the producer. Create a class named Producer and specify that it implements the Runnable interface.
package com.packtpub.java7.concurrency.chapter3.recipe7.task; import java.util.List;
import java.util.concurrent.Exchanger; /**
* This class implements the producer
*
*/
public class Producer implements Runnable { /**
* Buffer to save the events produced
*/
private List<String> buffer; /**
* Exchager to synchronize with the consumer
*/
private final Exchanger<List<String>> exchanger; /**
* Constructor of the class. Initializes its attributes
* @param buffer Buffer to save the events produced
* @param exchanger Exchanger to syncrhonize with the consumer
*/
public Producer (List<String> buffer, Exchanger<List<String>> exchanger){
this.buffer=buffer;
this.exchanger=exchanger;
} /**
* Main method of the producer. It produces 100 events. 10 cicles of 10 events.
* After produce 10 events, it uses the exchanger object to synchronize with
* the consumer. The producer sends to the consumer the buffer with ten events and
* receives from the consumer an empty buffer
*/
@Override
public void run() {
int cycle=1; for (int i=0; i<10; i++){
System.out.printf("Producer: Cycle %d\n",cycle); for (int j=0; j<10; j++){
String message="Event "+((i*10)+j);
System.out.printf("Producer: %s\n",message);
buffer.add(message);
} try {
/*
* Change the data buffer with the consumer
*/
buffer=exchanger.exchange(buffer);
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.printf("Producer: %d\n",buffer.size()); cycle++;
} } }
2. Second, implement the consumer. Create a class named Consumer and specify that it implements the Runnable interface.
package com.packtpub.java7.concurrency.chapter3.recipe7.task; import java.util.List;
import java.util.concurrent.Exchanger; /**
* This class implements the consumer of the example
*
*/
public class Consumer implements Runnable { /**
* Buffer to save the events produced
*/
private List<String> buffer; /**
* Exchager to synchronize with the consumer
*/
private final Exchanger<List<String>> exchanger; /**
* Constructor of the class. Initializes its attributes
* @param buffer Buffer to save the events produced
* @param exchanger Exchanger to syncrhonize with the consumer
*/
public Consumer(List<String> buffer, Exchanger<List<String>> exchanger){
this.buffer=buffer;
this.exchanger=exchanger;
} /**
* Main method of the producer. It consumes all the events produced by the Producer. After
* processes ten events, it uses the exchanger object to synchronize with
* the producer. It sends to the producer an empty buffer and receives a buffer with ten events
*/
@Override
public void run() {
int cycle=1; for (int i=0; i<10; i++){
System.out.printf("Consumer: Cycle %d\n",cycle); try {
// Wait for the produced data and send the empty buffer to the producer
buffer=exchanger.exchange(buffer);
} catch (InterruptedException e) {
e.printStackTrace();
} System.out.printf("Consumer: %d\n",buffer.size()); for (int j=0; j<10; j++){
String message=buffer.get(0);
System.out.printf("Consumer: %s\n",message);
buffer.remove(0);
} cycle++;
} } }
3. Finally, implement the main class of the example by creating a class named Core and add the main() method to it.
package com.packtpub.java7.concurrency.chapter3.recipe7.core; import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger; import com.packtpub.java7.concurrency.chapter3.recipe7.task.Consumer;
import com.packtpub.java7.concurrency.chapter3.recipe7.task.Producer; /**
* Main class of the example
*
*/
public class Main { /**
* Main method of the example
* @param args
*/
public static void main(String[] args) { // Creates two buffers
List<String> buffer1=new ArrayList<>();
List<String> buffer2=new ArrayList<>(); // Creates the exchanger
Exchanger<List<String>> exchanger=new Exchanger<>(); // Creates the producer
Producer producer=new Producer(buffer1, exchanger);
// Creates the consumer
Consumer consumer=new Consumer(buffer2, exchanger); // Creates and starts the threads
Thread threadProducer=new Thread(producer);
Thread threadConsumer=new Thread(consumer); threadProducer.start();
threadConsumer.start(); } }
The consumer begins with an empty buffer and calls Exchanger to synchronize with the producer. It needs data to consume. The producer begins its execution with an empty buffer. It creates 10 strings, stores it in the buffer, and uses the exchanger to synchronize with the consumer.
At this point, both threads (producer and consumer) are in Exchanger and it changes the data structures, so when the consumer returns from the exchange() method, it will have a buffer with 10 strings. When the producer returns from the exchange() method, it will have an empty buffer to fill again. This operation will be repeated 10 times.
If you execute the example, you will see how producer and consumer do their jobs concurrently and how the two objects interchange their buffers in every step. As it occurs with other synchronization utilities, the first thread that calls the exchange() method was put to sleep until the other threads arrived.
Exchanger, Changing data between concurrent tasks的更多相关文章
- 未能从程序集 C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Data.Entity.Build.Tasks.dll 加载任务“EntityClean”
问题: 未能从程序集 C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Data.Entity.Build.Tasks.dll 加载任务“Entity ...
- Fork and Join: Java Can Excel at Painless Parallel Programming Too!---转
原文地址:http://www.oracle.com/technetwork/articles/java/fork-join-422606.html Multicore processors are ...
- java.util.concurrent.Exchanger应用范例与原理浅析--转载
一.简介 Exchanger是自jdk1.5起开始提供的工具套件,一般用于两个工作线程之间交换数据.在本文中我将采取由浅入深的方式来介绍分析这个工具类.首先我们来看看官方的api文档中的叙述: A ...
- java Concurrent包学习笔记(六):Exchanger
一.概述 Exchanger 是一个用于线程间协作的工具类,Exchanger用于进行线程间的数据交换,它提供一个同步点,在这个同步点,两个线程可以交换彼此的数据.这两个线程通过exchange 方法 ...
- 并发编程-concurrent指南-交换机Exchanger
java.util.concurrent包中的Exchanger类可用于两个线程之间交换信息.可简单地将Exchanger对象理解为一个包含两个格子的容器,通过exchanger方法可以向两个格子中填 ...
- Java Concurrency - Concurrent Collections
Data structures are a basic element in programming. Almost every program uses one or more types of d ...
- JUC——线程同步辅助工具类(Exchanger,CompletableFuture)
Exchanger交换空间 如果现在有两个线程,一个线程负责生产数据,另外一个线程负责消费数据,那么这个两个线程之间一定会存在一个公共的区域,那么这个区域的实现在JUC包之中称为Exchanger. ...
- Java并发编程原理与实战二十九:Exchanger
一.简介 前面三篇博客分别介绍了CyclicBarrier.CountDownLatch.Semaphore,现在介绍并发工具类中的最后一个Exchange.Exchange是最简单的也是最复杂的,简 ...
- 并发新构件之Exchanger:交换器
Exchanger:JDK描述:可以在对中对元素进行配对和交换的线程的同步点.每个线程将条目上的某个方法呈现给 exchange 方法,与伙伴线程进行匹配,并且在返回时接收其伙伴的对象.Exchang ...
随机推荐
- 自己安装的几个Eclipse插件
http://eclipsenotepad.sourceforge.net This plugin has the simple objective to let developers write s ...
- HDU-4671 Backup Plan 构造解
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4671 假设是3 m,首先按照第一列按照1 2 3 1 2 3 1...排下去,然后个数就是一个 (m/ ...
- Django中的Model(操作表)
Model 操作表 一.基本操作 # 增 models.Tb1.objects.create(c1='xx', c2='oo') #增加一条数据,可以接受字典类型数据 **kwargs obj = m ...
- PT100运算放大器电路
运放输出电压<=运放电源电压,电源电压能决定它的最大输出能力即动态范围,若是电源为0-5v,则输出就只能在这之间. 其次要是放大电路,反馈必须接成负反馈 由于我这次使用的电源是5V,要是采用两 ...
- SecureCRT配置显示的字符集
- 好的git教程
1.GitHub使用教程for VS2012 http://www.cnblogs.com/yc-755909659/p/3753355.html
- 【WIN32进阶之路】:线程同步技术纲要
前面博客讲了互斥量(MUTEX)和关键段(CRITICAL SECTION)的使用,想来总觉不妥,就如盲人摸象一般,窥其一脚而言象,难免以偏概全,追加一篇博客查遗补漏. win32下的线程同步技术分为 ...
- 如何避免regionServer宕机
为什么regionserver 和Zookeeper的session expired? 可能的原因有 1. 网络不好. 2. Java full GC, 这会block所有的线程.如果时间比较长,也会 ...
- 秀一套每秒处理1500+个事务的profile
秀一套每秒处理1500+个事务的profile,真实生产环境
- iOS开发——新特性OC篇&Objective新特性
Objective新特性 Overview 自 WWDC 2015 推出和开源 Swift 2.0 后,大家对 Swift 的热情又一次高涨起来,在羡慕创业公司的朋友们大谈 Swift 新特性的同时, ...