Merge remote-tracking branch 'upstream/master'
This commit is contained in:
commit
37cfa4b295
@ -6,45 +6,44 @@ import com.iluwatar.observer.generic.GWeather;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* The Observer pattern is a software design pattern in which an object, called
|
* The Observer pattern is a software design pattern in which an object, called the subject,
|
||||||
* the subject, maintains a list of its dependents, called observers, and notifies
|
* maintains a list of its dependents, called observers, and notifies them automatically of any
|
||||||
* them automatically of any state changes, usually by calling one of their methods.
|
* state changes, usually by calling one of their methods. It is mainly used to implement
|
||||||
* It is mainly used to implement distributed event handling systems. The Observer
|
* distributed event handling systems. The Observer pattern is also a key part in the familiar
|
||||||
* pattern is also a key part in the familiar model–view–controller (MVC) architectural
|
* model–view–controller (MVC) architectural pattern. The Observer pattern is implemented in
|
||||||
* pattern. The Observer pattern is implemented in numerous programming libraries and
|
* numerous programming libraries and systems, including almost all GUI toolkits.
|
||||||
* systems, including almost all GUI toolkits.
|
|
||||||
* <p>
|
* <p>
|
||||||
* In this example {@link Weather} has a state that can be observed. The {@link Orcs}
|
* In this example {@link Weather} has a state that can be observed. The {@link Orcs} and
|
||||||
* and {@link Hobbits} register as observers and receive notifications when the
|
* {@link Hobbits} register as observers and receive notifications when the {@link Weather} changes.
|
||||||
* {@link Weather} changes.
|
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class App {
|
public class App {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Program entry point
|
* Program entry point
|
||||||
* @param args command line args
|
*
|
||||||
*/
|
* @param args command line args
|
||||||
public static void main(String[] args) {
|
*/
|
||||||
|
public static void main(String[] args) {
|
||||||
|
|
||||||
Weather weather = new Weather();
|
Weather weather = new Weather();
|
||||||
weather.addObserver(new Orcs());
|
weather.addObserver(new Orcs());
|
||||||
weather.addObserver(new Hobbits());
|
weather.addObserver(new Hobbits());
|
||||||
|
|
||||||
weather.timePasses();
|
weather.timePasses();
|
||||||
weather.timePasses();
|
weather.timePasses();
|
||||||
weather.timePasses();
|
weather.timePasses();
|
||||||
weather.timePasses();
|
weather.timePasses();
|
||||||
|
|
||||||
// Generic observer inspired by Java Generics and Collection by Naftalin & Wadler
|
// Generic observer inspired by Java Generics and Collection by Naftalin & Wadler
|
||||||
System.out.println("\n--Running generic version--");
|
System.out.println("\n--Running generic version--");
|
||||||
GWeather gWeather = new GWeather();
|
GWeather gWeather = new GWeather();
|
||||||
gWeather.addObserver(new GOrcs());
|
gWeather.addObserver(new GOrcs());
|
||||||
gWeather.addObserver(new GHobbits());
|
gWeather.addObserver(new GHobbits());
|
||||||
|
|
||||||
gWeather.timePasses();
|
gWeather.timePasses();
|
||||||
gWeather.timePasses();
|
gWeather.timePasses();
|
||||||
gWeather.timePasses();
|
gWeather.timePasses();
|
||||||
gWeather.timePasses();
|
gWeather.timePasses();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,24 +7,23 @@ package com.iluwatar.observer;
|
|||||||
*/
|
*/
|
||||||
public class Hobbits implements WeatherObserver {
|
public class Hobbits implements WeatherObserver {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void update(WeatherType currentWeather) {
|
public void update(WeatherType currentWeather) {
|
||||||
switch (currentWeather) {
|
switch (currentWeather) {
|
||||||
case COLD:
|
case COLD:
|
||||||
System.out.println("The hobbits are shivering in the cold weather.");
|
System.out.println("The hobbits are shivering in the cold weather.");
|
||||||
break;
|
break;
|
||||||
case RAINY:
|
case RAINY:
|
||||||
System.out.println("The hobbits look for cover from the rain.");
|
System.out.println("The hobbits look for cover from the rain.");
|
||||||
break;
|
break;
|
||||||
case SUNNY:
|
case SUNNY:
|
||||||
System.out.println("The happy hobbits bade in the warm sun.");
|
System.out.println("The happy hobbits bade in the warm sun.");
|
||||||
break;
|
break;
|
||||||
case WINDY:
|
case WINDY:
|
||||||
System.out.println("The hobbits hold their hats tightly in the windy weather.");
|
System.out.println("The hobbits hold their hats tightly in the windy weather.");
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,24 +7,23 @@ package com.iluwatar.observer;
|
|||||||
*/
|
*/
|
||||||
public class Orcs implements WeatherObserver {
|
public class Orcs implements WeatherObserver {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void update(WeatherType currentWeather) {
|
public void update(WeatherType currentWeather) {
|
||||||
switch (currentWeather) {
|
switch (currentWeather) {
|
||||||
case COLD:
|
case COLD:
|
||||||
System.out.println("The orcs are freezing cold.");
|
System.out.println("The orcs are freezing cold.");
|
||||||
break;
|
break;
|
||||||
case RAINY:
|
case RAINY:
|
||||||
System.out.println("The orcs are dripping wet.");
|
System.out.println("The orcs are dripping wet.");
|
||||||
break;
|
break;
|
||||||
case SUNNY:
|
case SUNNY:
|
||||||
System.out.println("The sun hurts the orcs' eyes.");
|
System.out.println("The sun hurts the orcs' eyes.");
|
||||||
break;
|
break;
|
||||||
case WINDY:
|
case WINDY:
|
||||||
System.out.println("The orc smell almost vanishes in the wind.");
|
System.out.println("The orc smell almost vanishes in the wind.");
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -5,38 +5,38 @@ import java.util.List;
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
* Weather can be observed by implementing {@link WeatherObserver} interface and
|
* Weather can be observed by implementing {@link WeatherObserver} interface and registering as
|
||||||
* registering as listener.
|
* listener.
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class Weather {
|
public class Weather {
|
||||||
|
|
||||||
private WeatherType currentWeather;
|
private WeatherType currentWeather;
|
||||||
private List<WeatherObserver> observers;
|
private List<WeatherObserver> observers;
|
||||||
|
|
||||||
public Weather() {
|
public Weather() {
|
||||||
observers = new ArrayList<>();
|
observers = new ArrayList<>();
|
||||||
currentWeather = WeatherType.SUNNY;
|
currentWeather = WeatherType.SUNNY;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addObserver(WeatherObserver obs) {
|
public void addObserver(WeatherObserver obs) {
|
||||||
observers.add(obs);
|
observers.add(obs);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void removeObserver(WeatherObserver obs) {
|
public void removeObserver(WeatherObserver obs) {
|
||||||
observers.remove(obs);
|
observers.remove(obs);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void timePasses() {
|
public void timePasses() {
|
||||||
WeatherType[] enumValues = WeatherType.values();
|
WeatherType[] enumValues = WeatherType.values();
|
||||||
currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
|
currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
|
||||||
System.out.println("The weather changed to " + currentWeather + ".");
|
System.out.println("The weather changed to " + currentWeather + ".");
|
||||||
notifyObservers();
|
notifyObservers();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void notifyObservers() {
|
private void notifyObservers() {
|
||||||
for (WeatherObserver obs : observers) {
|
for (WeatherObserver obs : observers) {
|
||||||
obs.update(currentWeather);
|
obs.update(currentWeather);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,6 @@ package com.iluwatar.observer;
|
|||||||
*/
|
*/
|
||||||
public interface WeatherObserver {
|
public interface WeatherObserver {
|
||||||
|
|
||||||
void update(WeatherType currentWeather);
|
void update(WeatherType currentWeather);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -7,11 +7,10 @@ package com.iluwatar.observer;
|
|||||||
*/
|
*/
|
||||||
public enum WeatherType {
|
public enum WeatherType {
|
||||||
|
|
||||||
SUNNY, RAINY, WINDY, COLD;
|
SUNNY, RAINY, WINDY, COLD;
|
||||||
|
|
||||||
@Override
|
|
||||||
public String toString() {
|
|
||||||
return this.name().toLowerCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return this.name().toLowerCase();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,23 +8,23 @@ import com.iluwatar.observer.WeatherType;
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class GHobbits implements Race {
|
public class GHobbits implements Race {
|
||||||
@Override
|
@Override
|
||||||
public void update(GWeather weather, WeatherType weatherType) {
|
public void update(GWeather weather, WeatherType weatherType) {
|
||||||
switch (weatherType) {
|
switch (weatherType) {
|
||||||
case COLD:
|
case COLD:
|
||||||
System.out.println("The hobbits are shivering in the cold weather.");
|
System.out.println("The hobbits are shivering in the cold weather.");
|
||||||
break;
|
break;
|
||||||
case RAINY:
|
case RAINY:
|
||||||
System.out.println("The hobbits look for cover from the rain.");
|
System.out.println("The hobbits look for cover from the rain.");
|
||||||
break;
|
break;
|
||||||
case SUNNY:
|
case SUNNY:
|
||||||
System.out.println("The happy hobbits bade in the warm sun.");
|
System.out.println("The happy hobbits bade in the warm sun.");
|
||||||
break;
|
break;
|
||||||
case WINDY:
|
case WINDY:
|
||||||
System.out.println("The hobbits hold their hats tightly in the windy weather.");
|
System.out.println("The hobbits hold their hats tightly in the windy weather.");
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,24 +8,24 @@ import com.iluwatar.observer.WeatherType;
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public class GOrcs implements Race {
|
public class GOrcs implements Race {
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void update(GWeather weather, WeatherType weatherType) {
|
public void update(GWeather weather, WeatherType weatherType) {
|
||||||
switch (weatherType) {
|
switch (weatherType) {
|
||||||
case COLD:
|
case COLD:
|
||||||
System.out.println("The orcs are freezing cold.");
|
System.out.println("The orcs are freezing cold.");
|
||||||
break;
|
break;
|
||||||
case RAINY:
|
case RAINY:
|
||||||
System.out.println("The orcs are dripping wet.");
|
System.out.println("The orcs are dripping wet.");
|
||||||
break;
|
break;
|
||||||
case SUNNY:
|
case SUNNY:
|
||||||
System.out.println("The sun hurts the orcs' eyes.");
|
System.out.println("The sun hurts the orcs' eyes.");
|
||||||
break;
|
break;
|
||||||
case WINDY:
|
case WINDY:
|
||||||
System.out.println("The orc smell almost vanishes in the wind.");
|
System.out.println("The orc smell almost vanishes in the wind.");
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
break;
|
break;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,16 +9,16 @@ import com.iluwatar.observer.WeatherType;
|
|||||||
*/
|
*/
|
||||||
public class GWeather extends Observable<GWeather, Race, WeatherType> {
|
public class GWeather extends Observable<GWeather, Race, WeatherType> {
|
||||||
|
|
||||||
private WeatherType currentWeather;
|
private WeatherType currentWeather;
|
||||||
|
|
||||||
public GWeather() {
|
public GWeather() {
|
||||||
currentWeather = WeatherType.SUNNY;
|
currentWeather = WeatherType.SUNNY;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void timePasses() {
|
public void timePasses() {
|
||||||
WeatherType[] enumValues = WeatherType.values();
|
WeatherType[] enumValues = WeatherType.values();
|
||||||
currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
|
currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length];
|
||||||
System.out.println("The weather changed to " + currentWeather + ".");
|
System.out.println("The weather changed to " + currentWeather + ".");
|
||||||
notifyObservers(currentWeather);
|
notifyObservers(currentWeather);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -12,20 +12,20 @@ import java.util.concurrent.CopyOnWriteArrayList;
|
|||||||
*/
|
*/
|
||||||
public abstract class Observable<S extends Observable<S, O, A>, O extends Observer<S, O, A>, A> {
|
public abstract class Observable<S extends Observable<S, O, A>, O extends Observer<S, O, A>, A> {
|
||||||
|
|
||||||
protected List<O> observers;
|
protected List<O> observers;
|
||||||
|
|
||||||
public Observable() {
|
public Observable() {
|
||||||
this.observers = new CopyOnWriteArrayList<>();
|
this.observers = new CopyOnWriteArrayList<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void addObserver(O observer) {
|
public void addObserver(O observer) {
|
||||||
this.observers.add(observer);
|
this.observers.add(observer);
|
||||||
}
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
public void notifyObservers(A argument) {
|
public void notifyObservers(A argument) {
|
||||||
for (O observer : observers) {
|
for (O observer : observers) {
|
||||||
observer.update((S) this, argument);
|
observer.update((S) this, argument);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -10,5 +10,5 @@ package com.iluwatar.observer.generic;
|
|||||||
*/
|
*/
|
||||||
public interface Observer<S extends Observable<S, O, A>, O extends Observer<S, O, A>, A> {
|
public interface Observer<S extends Observable<S, O, A>, O extends Observer<S, O, A>, A> {
|
||||||
|
|
||||||
void update(S subject, A argument);
|
void update(S subject, A argument);
|
||||||
}
|
}
|
||||||
|
@ -11,9 +11,9 @@ import com.iluwatar.observer.App;
|
|||||||
*/
|
*/
|
||||||
public class AppTest {
|
public class AppTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void test() {
|
public void test() {
|
||||||
String[] args = {};
|
String[] args = {};
|
||||||
App.main(args);
|
App.main(args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
1
pom.xml
1
pom.xml
@ -56,6 +56,7 @@
|
|||||||
<module>execute-around</module>
|
<module>execute-around</module>
|
||||||
<module>property</module>
|
<module>property</module>
|
||||||
<module>intercepting-filter</module>
|
<module>intercepting-filter</module>
|
||||||
|
<module>producer-consumer</module>
|
||||||
<module>poison-pill</module>
|
<module>poison-pill</module>
|
||||||
<module>lazy-loading</module>
|
<module>lazy-loading</module>
|
||||||
<module>service-layer</module>
|
<module>service-layer</module>
|
||||||
|
BIN
producer-consumer/etc/producer-consumer.png
Normal file
BIN
producer-consumer/etc/producer-consumer.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 26 KiB |
74
producer-consumer/etc/producer-consumer.ucls
Normal file
74
producer-consumer/etc/producer-consumer.ucls
Normal 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>
|
22
producer-consumer/index.md
Normal file
22
producer-consumer/index.md
Normal 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..
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
**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
18
producer-consumer/pom.xml
Normal 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>
|
@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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()));
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -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));
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user