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 ...
随机推荐
- jexus asp.net Linux Web Server
Jexus简介 Jexus web server for linux 是运行在Linux上的Web服务器.其安装和部署及其简单,直接支持Asp.net . 下载Jexus wget http://li ...
- Barcode記錄
.net開源框架 Barcode Rendering Framework URL:http://barcoderender.codeplex.com/releases/view/91902 可產生BR ...
- xampp配置host和httpd可以随意访问任何本机的地址
1.修改host 不管你用的是什么系统,windows, mac,电脑上都会有一个 hosts 文件,修改这个文件,可以改变主机名所对应的 ip 地址.比如你安装了 Web 开发环境(MAMP 或 W ...
- PowerDesigner 面向对象模型(OOM)
PowerDesigner 面向对象模型(OOM)说明 nulljavasystemstringpowerbuilderclass 目录(?)[+] 一. OOM 简介 Object- ...
- session和request的区别
request 请求对象 请求中保存请求过程中需要的参数 比如另一个页面需要使用的对象编号,list,map等,请求结束,就失效了 session 会话对象 除非关闭会话(到时间通常为30分钟,或者关 ...
- node.js在windows下的学习笔记(7)---express的app.js的详细配置说明
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon') ...
- TigerDLNA for ios 集成Tlplayer
好久没有写博客了,这次带着TigerDLNA for ios 跟大家见面 什么都不说先上图 1.优点 优点由于libTigerDLNA使用uiview封装,所以大家可以很方便的集成到自己的项目中.由于 ...
- string中find函数的使用
9.47 编写程序,首先查找string"ab2c3d7R4E6"中的每个数字字符,然后查找其中每个字母字符.编写两个版本的程序,第一个要使用find_first_of,第二个要使 ...
- Apache Rewrite 服务器变量
Apache提供给rewirte模块的环境变量大概分成5个类型. 第一部分: HTTP headers 部分参数 参数名称: HTTP_USER_AGENT 样例参考值: Mozilla/5.0 (W ...
- Spring JTA multiple resource transactions in Tomcat with Atomikos example--转载
原文地址:http://www.javacodegeeks.com/2013/07/spring-jta-multiple-resource-transactions-in-tomcat-with-a ...