#271 implements producer-consumer

This commit is contained in:
hongsw 2015-10-28 09:55:05 +08:00
parent a2b8359ab5
commit 07faa2f625
11 changed files with 299 additions and 0 deletions

View File

@ -56,6 +56,7 @@
<module>execute-around</module>
<module>property</module>
<module>intercepting-filter</module>
<module>producer-consumer</module>
<module>poison-pill</module>
<module>lazy-loading</module>
<module>service-layer</module>

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

View File

@ -0,0 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<class-diagram version="1.1.8" icons="true" automaticImage="PNG" always-add-relationships="false" generalizations="true"
realizations="true" associations="true" dependencies="false" nesting-relationships="true">
<class id="1" language="java" name="com.iluwatar.producer.consumer.Item" project="producer-consumer"
file="/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Item.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="415" y="378"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="2" language="java" name="com.iluwatar.producer.consumer.Producer" project="producer-consumer"
file="/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Producer.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="150" y="191"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="3" language="java" name="com.iluwatar.producer.consumer.Consumer" project="producer-consumer"
file="/producer-consumer/src/main/java/com/iluwatar/producer/consumer/Consumer.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="675" y="186"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<class id="4" language="java" name="com.iluwatar.producer.consumer.ItemQueue" project="producer-consumer"
file="/producer-consumer/src/main/java/com/iluwatar/producer/consumer/ItemQueue.java" binary="false"
corner="BOTTOM_RIGHT">
<position height="-1" width="-1" x="415" y="187"/>
<display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</display>
</class>
<association id="5">
<end type="SOURCE" refId="3" navigable="false">
<attribute id="6" name="queue"/>
<multiplicity id="7" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="4" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="8">
<end type="SOURCE" refId="4" navigable="false">
<attribute id="9" name="queue"/>
<multiplicity id="10" minimum="0" maximum="2147483647"/>
</end>
<end type="TARGET" refId="1" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<association id="11">
<end type="SOURCE" refId="2" navigable="false">
<attribute id="12" name="queue"/>
<multiplicity id="13" minimum="0" maximum="1"/>
</end>
<end type="TARGET" refId="4" navigable="true"/>
<display labels="true" multiplicity="true"/>
</association>
<classifier-display autosize="true" stereotype="true" package="true" initial-value="false" signature="true"
sort-features="false" accessors="true" visibility="true">
<attributes public="true" package="true" protected="true" private="true" static="true"/>
<operations public="true" package="true" protected="true" private="true" static="true"/>
</classifier-display>
<association-display labels="true" multiplicity="true"/>
</class-diagram>

View File

@ -0,0 +1,22 @@
---
layout: pattern
title: Producer Consumer
folder: producer-consumer
permalink: /patterns/producer-consumer/
categories: Other
tags: Java
---
**Intent:** Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces
coupling between Producer and Consumer by separating Identification of work with Execution of
Work..
![alt text](./etc/producer-consumer.png "Producer Consumer")
**Applicability:** Use the Producer Consumer idiom when
* decouple system by separate work in two process produce and consume.
* addresses the issue of different timing require to produce work or consuming work

18
producer-consumer/pom.xml Normal file
View File

@ -0,0 +1,18 @@
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.7.0</version>
</parent>
<artifactId>producer-consumer</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,57 @@
package com.iluwatar.producer.consumer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Producer Consumer Design pattern is a classic concurrency or threading pattern which reduces
* coupling between Producer and Consumer by separating Identification of work with Execution of
* Work.
* <p>
* In producer consumer design pattern a shared queue is used to control the flow and this
* separation allows you to code producer and consumer separately. It also addresses the issue of
* different timing require to produce item or consuming item. by using producer consumer pattern
* both Producer and Consumer Thread can work with different speed.
*
*/
public class App {
/**
* Program entry point
*
* @param args command line args
*/
public static void main(String[] args) {
ItemQueue queue = new ItemQueue();
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 2; i++) {
final Producer producer = new Producer("Producer_" + i, queue);
executorService.submit(() -> {
while (true) {
producer.produce();
}
});
};
for (int i = 0; i < 3; i++) {
final Consumer consumer = new Consumer("Consumer_" + i, queue);
executorService.submit(() -> {
while (true) {
consumer.consume();
}
});
}
executorService.shutdown();
try {
executorService.awaitTermination(10, TimeUnit.SECONDS);
executorService.shutdownNow();
} catch (InterruptedException e) {
System.out.println("Error waiting for ExecutorService shutdown");
}
}
}

View File

@ -0,0 +1,24 @@
package com.iluwatar.producer.consumer;
/**
* Class responsible for consume the {@link Item} produced by {@link Producer}
*/
public class Consumer {
private final ItemQueue queue;
private final String name;
public Consumer(String name, ItemQueue queue) {
this.name = name;
this.queue = queue;
}
public void consume() throws InterruptedException {
Item item = queue.take();
System.out.println(String.format("Consumer [%s] consume item [%s] produced by [%s]", name,
item.getId(), item.getProducer()));
}
}

View File

@ -0,0 +1,27 @@
package com.iluwatar.producer.consumer;
/**
* Class take part of an {@link Producer}-{@link Consumer} exchange.
*/
public class Item {
private String producer;
private int id;
public Item(String producer, int id) {
this.id = id;
this.producer = producer;
}
public int getId() {
return id;
}
public String getProducer() {
return producer;
}
}

View File

@ -0,0 +1,27 @@
package com.iluwatar.producer.consumer;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Class as a channel for {@link Producer}-{@link Consumer} exchange.
*/
public class ItemQueue {
private LinkedBlockingQueue<Item> queue;
public ItemQueue() {
queue = new LinkedBlockingQueue<Item>(5);
}
public void put(Item item) throws InterruptedException {
queue.put(item);
}
public Item take() throws InterruptedException {
return queue.take();
}
}

View File

@ -0,0 +1,29 @@
package com.iluwatar.producer.consumer;
import java.util.Random;
/**
* Class responsible for producing unit of work that can be expressed as {@link Item} and submitted
* to queue
*/
public class Producer {
private final ItemQueue queue;
private final String name;
private int itemId = 0;
public Producer(String name, ItemQueue queue) {
this.name = name;
this.queue = queue;
}
public void produce() throws InterruptedException {
Item item = new Item(name, itemId++);
queue.put(item);
Random random = new Random();
Thread.sleep(random.nextInt(2000));
}
}

View File

@ -0,0 +1,20 @@
package com.iluwatar.poison.pill;
import org.junit.Test;
import com.iluwatar.producer.consumer.App;
/**
*
* Application test
*
*/
public class AppTest {
@Test
public void test() throws Exception {
String[] args = {};
App.main(args);
}
}