Update according to review comments #397

- Added descriptions
- Added junit tests
- Added javadoc
- Added index.md
- Added class diagrams
This commit is contained in:
gwildor28 2016-03-24 18:13:37 +00:00
parent 3ed3bc1fa5
commit 6e4b269939
20 changed files with 273 additions and 34 deletions

BIN
mutex/etc/mutex.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

30
mutex/index.md Normal file
View File

@ -0,0 +1,30 @@
---
layout: pattern
title: Mutex
folder: mutex
permalink: /patterns/mutex/
categories: Lock
tags:
- Java
- Difficulty-Beginner
---
## Also known as
Mutual Exclusion Lock
Binary Semaphore
## Intent
Create a lock which only allows a single thread to access a resource at any one instant.
![alt text](./etc/mutex.png "Mutex")
## Applicability
Use a Mutex when
* you need to prevent two threads accessing a critical section at the same time
* concurrent access to a resource could lead to a race condition
## Credits
* [Lock (computer science)] (http://en.wikipedia.org/wiki/Lock_(computer_science))
* [Semaphores] (http://tutorials.jenkov.com/java-concurrency/semaphores.html)

View File

@ -2,7 +2,7 @@
<!-- <!--
The MIT License The MIT License
Copyright (c) 2014 Ilkka Seppälä Copyright (c) 2014 Ilkka Sepp<EFBFBD>l<EFBFBD>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
@ -32,4 +32,11 @@
<version>1.11.0-SNAPSHOT</version> <version>1.11.0-SNAPSHOT</version>
</parent> </parent>
<artifactId>mutex</artifactId> <artifactId>mutex</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project> </project>

View File

@ -23,7 +23,15 @@
package com.iluwatar.mutex; package com.iluwatar.mutex;
/** /**
* App. * A Mutex prevents multiple threads from accessing a resource simultaneously.
* <p>
* In this example we have two thieves who are taking beans from a jar.
* Only one thief can take a bean at a time. This is ensured by a Mutex lock
* which must be acquired in order to access the jar. Each thief attempts to
* acquire the lock, take a bean and then release the lock. If the lock has
* already been acquired, the thief will be prevented from continuing (blocked)
* until the lock has been released. The thieves stop taking beans once there
* are no beans left to take.
*/ */
public class App { public class App {

View File

@ -23,12 +23,20 @@
package com.iluwatar.mutex; package com.iluwatar.mutex;
/** /**
* Jar. * A Jar has a resource of beans which can only be accessed by a single Thief
* (thread) at any one time. A Mutex lock is used to prevent more than one Thief
* taking a bean simultaneously.
*/ */
public class Jar { public class Jar {
private Lock lock; /**
* The lock which must be acquired to access the beans resource.
*/
private final Lock lock;
/**
* The resource within the jar.
*/
private int beans = 1000; private int beans = 1000;
public Jar(Lock lock) { public Jar(Lock lock) {
@ -36,7 +44,7 @@ public class Jar {
} }
/** /**
* takeBean method * Method for a thief to take a bean.
*/ */
public boolean takeBean(Thief thief) { public boolean takeBean(Thief thief) {
boolean success = false; boolean success = false;

View File

@ -23,7 +23,7 @@
package com.iluwatar.mutex; package com.iluwatar.mutex;
/** /**
* Lock. * Lock is an interface for a lock which can be acquired and released.
*/ */
public interface Lock { public interface Lock {

View File

@ -23,11 +23,20 @@
package com.iluwatar.mutex; package com.iluwatar.mutex;
/** /**
* Mutex. * Mutex is an implementation of a mutual exclusion lock.
*/ */
public class Mutex implements Lock { public class Mutex implements Lock {
private Object owner = null;
/**
* The current owner of the lock.
*/
private Object owner;
/**
* Method called by a thread to acquire the lock. If the lock has already
* been acquired this will wait until the lock has been released to
* re-attempt the acquire.
*/
@Override @Override
public synchronized void acquire() throws InterruptedException { public synchronized void acquire() throws InterruptedException {
while (owner != null) { while (owner != null) {
@ -37,6 +46,9 @@ public class Mutex implements Lock {
owner = Thread.currentThread(); owner = Thread.currentThread();
} }
/**
* Method called by a thread to release the lock.
*/
@Override @Override
public synchronized void release() { public synchronized void release() {
owner = null; owner = null;

View File

@ -23,19 +23,30 @@
package com.iluwatar.mutex; package com.iluwatar.mutex;
/** /**
* Thief. * Thief is a class which continually tries to acquire a jar and take a bean
* from it. When the jar is empty the thief stops.
*/ */
public class Thief extends Thread { public class Thief extends Thread {
private String name; /**
* The name of the thief.
*/
private final String name;
private Jar jar; /**
* The jar
*/
private final Jar jar;
public Thief(String name, Jar jar) { public Thief(String name, Jar jar) {
this.name = name; this.name = name;
this.jar = jar; this.jar = jar;
} }
/**
* In the run method the thief repeatedly tries to take a bean until none
* are left.
*/
@Override @Override
public void run() { public void run() {
int beans = 0; int beans = 0;

View File

@ -0,0 +1,34 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.mutex;
import org.junit.Test;
import java.io.IOException;
public class AppTest{
@Test
public void test() throws IOException {
String[] args = {};
App.main(args);
}
}

BIN
semaphore/etc/semaphore.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

33
semaphore/index.md Normal file
View File

@ -0,0 +1,33 @@
---
layout: pattern
title: Semaphore
folder: semaphore
permalink: /patterns/semaphore/
categories: Lock
tags:
- Java
- Difficulty-Beginner
---
## Also known as
Counting Semaphore
## Intent
Create a lock which mediates access to a pool of resources.
Only a limited number of threads, specified at the creation
of the semaphore, can access the resources at any given time.
A semaphore which only allows one concurrent access to a resource
is called a binary semaphore.
![alt text](./etc/semaphore.png "Semaphore")
## Applicability
Use a Semaphore when
* you have a pool of resources to allocate to different threads
* concurrent access to a resource could lead to a race condition
## Credits
* [Semaphore(programming)] (http://en.wikipedia.org/wiki/Semaphore_(programming))
* [Semaphores] (http://tutorials.jenkov.com/java-concurrency/semaphores.html)

View File

@ -2,7 +2,7 @@
<!-- <!--
The MIT License The MIT License
Copyright (c) 2014 Ilkka Seppälä Copyright (c) 2014 Ilkka Sepp<EFBFBD>l<EFBFBD>
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
@ -32,4 +32,11 @@
<version>1.11.0-SNAPSHOT</version> <version>1.11.0-SNAPSHOT</version>
</parent> </parent>
<artifactId>semaphore</artifactId> <artifactId>semaphore</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project> </project>

View File

@ -23,7 +23,14 @@
package com.iluwatar.semaphore; package com.iluwatar.semaphore;
/** /**
* App. * A Semaphore mediates access by a group of threads to a pool of resources.
* <p>
* In this example a group of customers are taking fruit from a fruit shop.
* There is a bowl each of apples, oranges and lemons. Only one customer can
* access a bowl simultaneously. A Semaphore is used to indicate how many
* resources are currently available and must be acquired in order for a bowl
* to be given to a customer. Customers continually try to take fruit until
* there is no fruit left in the shop.
*/ */
public class App { public class App {

View File

@ -23,13 +23,25 @@
package com.iluwatar.semaphore; package com.iluwatar.semaphore;
/** /**
* Customer. * A Customer attempts to repeatedly take Fruit from the FruitShop by
* taking Fruit from FruitBowl instances.
*/ */
public class Customer extends Thread { public class Customer extends Thread {
private String name; /**
private FruitShop fruitShop; * Name of the Customer.
private FruitBowl fruitBowl; */
private final String name;
/**
* The FruitShop he is using.
*/
private final FruitShop fruitShop;
/**
* Their bowl of Fruit.
*/
private final FruitBowl fruitBowl;
/** /**
* Customer constructor * Customer constructor
@ -41,7 +53,8 @@ public class Customer extends Thread {
} }
/** /**
* run method * The Customer repeatedly takes Fruit from the FruitShop until no Fruit
* remains.
*/ */
public void run() { public void run() {

View File

@ -23,7 +23,7 @@
package com.iluwatar.semaphore; package com.iluwatar.semaphore;
/** /**
* Fruit. * Fruit is a resource stored in a FruitBowl.
*/ */
public class Fruit { public class Fruit {

View File

@ -25,22 +25,32 @@ package com.iluwatar.semaphore;
import java.util.ArrayList; import java.util.ArrayList;
/** /**
* FruitBowl. * A FruitBowl contains Fruit.
*/ */
public class FruitBowl { public class FruitBowl {
private ArrayList<Fruit> fruit = new ArrayList<>(); private ArrayList<Fruit> fruit = new ArrayList<>();
/**
*
* @return The amount of Fruit left in the bowl.
*/
public int countFruit() { public int countFruit() {
return fruit.size(); return fruit.size();
} }
/**
* Put an item of Fruit into the bowl.
*
* @param f fruit
*/
public void put(Fruit f) { public void put(Fruit f) {
fruit.add(f); fruit.add(f);
} }
/** /**
* take method * Take an item of Fruit out of the bowl.
* @return The Fruit taken out of the bowl, or null if empty.
*/ */
public Fruit take() { public Fruit take() {
if (fruit.isEmpty()) { if (fruit.isEmpty()) {

View File

@ -23,22 +23,31 @@
package com.iluwatar.semaphore; package com.iluwatar.semaphore;
/** /**
* FruitShop. * A FruitShop contains three FruitBowl instances and controls access to them.
*/ */
public class FruitShop { public class FruitShop {
/**
* The FruitBowl instances stored in the class.
*/
private FruitBowl[] bowls = { private FruitBowl[] bowls = {
new FruitBowl(), new FruitBowl(),
new FruitBowl(), new FruitBowl(),
new FruitBowl() new FruitBowl()
}; };
/**
* Access flags for each of the FruitBowl instances.
*/
private boolean[] available = { private boolean[] available = {
true, true,
true, true,
true true
}; };
/**
* The Semaphore that controls access to the class resources.
*/
private Semaphore semaphore; private Semaphore semaphore;
/** /**
@ -54,12 +63,18 @@ public class FruitShop {
semaphore = new Semaphore(3); semaphore = new Semaphore(3);
} }
/**
*
* @return The amount of Fruit left in the shop.
*/
public synchronized int countFruit() { public synchronized int countFruit() {
return bowls[0].countFruit() + bowls[1].countFruit() + bowls[2].countFruit(); return bowls[0].countFruit() + bowls[1].countFruit() + bowls[2].countFruit();
} }
/** /**
* takeBowl method * Method called by Customer to get a FruitBowl from the shop. This method
* will try to acquire the Semaphore before returning the first available
* FruitBowl.
*/ */
public synchronized FruitBowl takeBowl() { public synchronized FruitBowl takeBowl() {
@ -88,7 +103,9 @@ public class FruitShop {
} }
/** /**
* returnBowl method * Method called by a Customer instance to return a FruitBowl to the shop.
* This method releases the Semaphore, making the FruitBowl available to
* another Customer.
*/ */
public synchronized void returnBowl(FruitBowl bowl) { public synchronized void returnBowl(FruitBowl bowl) {
if (bowl == bowls[0]) { if (bowl == bowls[0]) {

View File

@ -23,7 +23,7 @@
package com.iluwatar.semaphore; package com.iluwatar.semaphore;
/** /**
* Lock. * Lock is an interface for a lock which can be acquired and released.
*/ */
public interface Lock { public interface Lock {

View File

@ -23,10 +23,13 @@
package com.iluwatar.semaphore; package com.iluwatar.semaphore;
/** /**
* Semaphore. * Semaphore is an implementation of a semaphore lock.
*/ */
public class Semaphore implements Lock { public class Semaphore implements Lock {
/**
* The number of concurrent resource accesses which are allowed.
*/
private int counter; private int counter;
public Semaphore(int counter) { public Semaphore(int counter) {
@ -34,7 +37,9 @@ public class Semaphore implements Lock {
} }
/** /**
* acquire method * Method called by a thread to acquire the lock. If there are no resources
* available this will wait until the lock has been released to re-attempt
* the acquire.
*/ */
public synchronized void acquire() throws InterruptedException { public synchronized void acquire() throws InterruptedException {
while (counter == 0) { while (counter == 0) {
@ -43,6 +48,9 @@ public class Semaphore implements Lock {
counter = counter - 1; counter = counter - 1;
} }
/**
* Method called by a thread to release the lock.
*/
public synchronized void release() { public synchronized void release() {
counter = counter + 1; counter = counter + 1;
notify(); notify();

View File

@ -0,0 +1,34 @@
/**
* The MIT License
* Copyright (c) 2014 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.semaphore;
import org.junit.Test;
import java.io.IOException;
public class AppTest{
@Test
public void test() throws IOException {
String[] args = {};
App.main(args);
}
}