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 ...
随机推荐
- jqgrid在页面出来竖型滚动条自动调整列宽
在项目中使用jqgrid的时候,需要设置在页面竖型滚动条出来的时候,列宽进行调整 1. 判断jqgrid的宽度是否和页面的宽度不一致(判断滚动条是否出来) 2. 调整jqgrid的列宽,因为jqgri ...
- hdu5773--The All-purpose Zero(LIS变形)
题意:给一个非负整数的数列,其中0可以变成任意整数,包括负数,求最长上升子序列的长度. 题解:LIS是最简单的DP了,但是变形之后T^T真的没想到.数据范围是10^5,只能O(nlogn)的做法,所以 ...
- Android实例-处理隐藏输入法后不再显示问题(XE8+小米2)
结果: 1.可以处理再次显示问题,但缺点是每个控件都要处理一次,累.哪位大神有好的处理方法,请M我. 实例代码: unit Unit1; interface uses System.SysUtils, ...
- Oracle-PLSQL Developer使用笔记
1.新建菜单 command window ---->命令行,执行sql语句 sql window ---->执行sql语句,可导出CSV,TSV,HTML,XML等类型文件 report ...
- DTD - XML Building Blocks
The main building blocks of both XML and HTML documents are elements. The Building Blocks of XML Doc ...
- UVa 二分图匹配 Examples
这些都是刘汝佳的算法训练指南上的例题,基本包括了常见的几种二分图匹配的算法. 二分图是这样一个图,顶点分成两个不相交的集合X , Y中,其中同一个集合中没有边,所有的边关联在两个集合中. 给定一个二分 ...
- CSS3之边框图片border-image
CSS3中有关border的属性,还有很多,今天我将为大家介绍一个很好玩的属性——Border-image.有了CSS3之边框图片Border-image,我们可以轻松搞定圆角,轻松搞定很多之前难搞的 ...
- [五]SpringMvc学习-Restful风格实现
1.Restful风格的资源URL 无后缀资源的访问(csdn用法) 2.SpringMvc对Rest风格的支持 2.1将 /*.do改为/ 2.2 3.@PathVariable获取Url变量 @R ...
- 【WIN32进阶之路】:内存映射文件
第一章:源起 遇到一个问题,如果一个客户数据文件有2g大,客户要通过界面查询文件中的数据并用列表控件显示数据,要怎么处理这个文件才能让应用程序不会长时间无响应,客户感觉不到程序的卡顿? 第二章:解决 ...
- OC/Swift第三方添加出错解决方法
(未经同意,不得转载!) ------------------------华丽分割线-----------------------