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的更多相关文章

  1. 未能从程序集 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 ...

  2. 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 ...

  3. java.util.concurrent.Exchanger应用范例与原理浅析--转载

    一.简介   Exchanger是自jdk1.5起开始提供的工具套件,一般用于两个工作线程之间交换数据.在本文中我将采取由浅入深的方式来介绍分析这个工具类.首先我们来看看官方的api文档中的叙述: A ...

  4. java Concurrent包学习笔记(六):Exchanger

    一.概述 Exchanger 是一个用于线程间协作的工具类,Exchanger用于进行线程间的数据交换,它提供一个同步点,在这个同步点,两个线程可以交换彼此的数据.这两个线程通过exchange 方法 ...

  5. 并发编程-concurrent指南-交换机Exchanger

    java.util.concurrent包中的Exchanger类可用于两个线程之间交换信息.可简单地将Exchanger对象理解为一个包含两个格子的容器,通过exchanger方法可以向两个格子中填 ...

  6. Java Concurrency - Concurrent Collections

    Data structures are a basic element in programming. Almost every program uses one or more types of d ...

  7. JUC——线程同步辅助工具类(Exchanger,CompletableFuture)

    Exchanger交换空间 如果现在有两个线程,一个线程负责生产数据,另外一个线程负责消费数据,那么这个两个线程之间一定会存在一个公共的区域,那么这个区域的实现在JUC包之中称为Exchanger. ...

  8. Java并发编程原理与实战二十九:Exchanger

    一.简介 前面三篇博客分别介绍了CyclicBarrier.CountDownLatch.Semaphore,现在介绍并发工具类中的最后一个Exchange.Exchange是最简单的也是最复杂的,简 ...

  9. 并发新构件之Exchanger:交换器

    Exchanger:JDK描述:可以在对中对元素进行配对和交换的线程的同步点.每个线程将条目上的某个方法呈现给 exchange 方法,与伙伴线程进行匹配,并且在返回时接收其伙伴的对象.Exchang ...

随机推荐

  1. Android--应用开发3(Android layout XML属性)

    Android layout XML属性 转载:http://www.cnblogs.com/playing/archive/2011/04/07/2008620.html Layout对于迅速的搭建 ...

  2. dataStructure@ Binary Search Tree

    #include<iostream> #include<cstdio> #include<cstring> #include<limits> #incl ...

  3. 在windows2012&2008中设置防火墙允许filezilla的passive模式

    添加入战规则, 允许程序和服务 "filezilla" 被连接 只允许21端口通过防火墙是不够的.

  4. FZU 2176 easy problem (DFS序+树状数组)

    对于一颗树,dfs遍历为每个节点标号,在进入一个树是标号和在遍历完这个树的子树后标号,那么子树所有的标号都在这两个数之间,是一个连续的区间.(好神奇~~~) 这样每次操作一个结点的子树时,在每个点的开 ...

  5. Fun with layers

    Fun with layers 这篇文章的有些内容很奇怪,我根本就没有这种现象,所以暂时就这样吧 In this post, I’ll explain how to add a border, rou ...

  6. hdu 4607 (树形DP)

    当时比赛的时候我们找出来只要求出树的最长的边的节点数ans,如果要访问点的个数n小于ans距离直接就是n-1 如果大于的话就是(n-ans)*2+ans-1,当时求树的直径难倒我们了,都不会树形dp ...

  7. Redis集群的使用测试(Jedis客户端的使用)

    Redis集群的使用测试(Jedis客户端的使用)1.Jedis客户端建议升级到最新版(当前为2.7.3),这样对3.0.x集群有比较好的支持.https://github.com/xetorthio ...

  8. iOS 应用数据存储的常用方式

    iOS 开发中,经常会有将数据存储到本地的需求.比如一些数据的缓存,或者记录下用户的账号密码,记录下下次是否自动登录等,这些都需要将数据记录到本地.iOS中,数据存储到本地的常见方式有三种: 一: 使 ...

  9. 【转】Netty那点事(三)Channel中的Pipeline

    [原文]https://github.com/code4craft/netty-learning/blob/master/posts/ch3-pipeline.md Channel是理解和使用Nett ...

  10. 在ubuntu上面配置nginx实现反向代理

    1.下载nginx    官网:http://nginx.org/en/download.html    直接在服务器上下载 wget http://nginx.org/download/nginx- ...