Skip to content

Commit 534fb67

Browse files
committed
Merge pull request iluwatar#397 from gwildor28/master
Lock Pattern iluwatar#71: Added mutex and semaphore modules to demonstrate locks
2 parents 886ad7e + a284329 commit 534fb67

File tree

25 files changed

+1200
-6
lines changed

25 files changed

+1200
-6
lines changed

mutex/README.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
---
2+
layout: pattern
3+
title: Mutex
4+
folder: mutex
5+
permalink: /patterns/mutex/
6+
categories: Lock
7+
tags:
8+
- Java
9+
- Difficulty-Beginner
10+
---
11+
12+
## Also known as
13+
Mutual Exclusion Lock
14+
Binary Semaphore
15+
16+
## Intent
17+
Create a lock which only allows a single thread to access a resource at any one instant.
18+
19+
![alt text](./etc/mutex.png "Mutex")
20+
21+
## Applicability
22+
Use a Mutex when
23+
24+
* you need to prevent two threads accessing a critical section at the same time
25+
* concurrent access to a resource could lead to a race condition
26+
27+
## Credits
28+
29+
* [Lock (computer science)] (http://en.wikipedia.org/wiki/Lock_(computer_science))
30+
* [Semaphores] (http://tutorials.jenkov.com/java-concurrency/semaphores.html)

mutex/etc/mutex.png

12.4 KB
Loading

mutex/pom.xml

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?xml version="1.0"?>
2+
<!--
3+
4+
The MIT License
5+
Copyright (c) 2014 Ilkka Sepp�l�
6+
7+
Permission is hereby granted, free of charge, to any person obtaining a copy
8+
of this software and associated documentation files (the "Software"), to deal
9+
in the Software without restriction, including without limitation the rights
10+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
copies of the Software, and to permit persons to whom the Software is
12+
furnished to do so, subject to the following conditions:
13+
14+
The above copyright notice and this permission notice shall be included in
15+
all copies or substantial portions of the Software.
16+
17+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23+
THE SOFTWARE.
24+
25+
-->
26+
<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"
27+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
28+
<modelVersion>4.0.0</modelVersion>
29+
<parent>
30+
<groupId>com.iluwatar</groupId>
31+
<artifactId>java-design-patterns</artifactId>
32+
<version>1.12.0-SNAPSHOT</version>
33+
</parent>
34+
<artifactId>mutex</artifactId>
35+
<dependencies>
36+
<dependency>
37+
<groupId>junit</groupId>
38+
<artifactId>junit</artifactId>
39+
<scope>test</scope>
40+
</dependency>
41+
</dependencies>
42+
</project>
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package com.iluwatar.mutex;
24+
25+
/**
26+
* A Mutex prevents multiple threads from accessing a resource simultaneously.
27+
* <p>
28+
* In this example we have two thieves who are taking beans from a jar.
29+
* Only one thief can take a bean at a time. This is ensured by a Mutex lock
30+
* which must be acquired in order to access the jar. Each thief attempts to
31+
* acquire the lock, take a bean and then release the lock. If the lock has
32+
* already been acquired, the thief will be prevented from continuing (blocked)
33+
* until the lock has been released. The thieves stop taking beans once there
34+
* are no beans left to take.
35+
*/
36+
public class App {
37+
38+
/**
39+
* main method
40+
*/
41+
public static void main(String[] args) {
42+
Mutex mutex = new Mutex();
43+
Jar jar = new Jar(1000, mutex);
44+
Thief peter = new Thief("Peter", jar);
45+
Thief john = new Thief("John", jar);
46+
peter.start();
47+
john.start();
48+
}
49+
50+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package com.iluwatar.mutex;
24+
25+
/**
26+
* A Jar has a resource of beans which can only be accessed by a single Thief
27+
* (thread) at any one time. A Mutex lock is used to prevent more than one Thief
28+
* taking a bean simultaneously.
29+
*/
30+
public class Jar {
31+
32+
/**
33+
* The lock which must be acquired to access the beans resource.
34+
*/
35+
private final Lock lock;
36+
37+
/**
38+
* The resource within the jar.
39+
*/
40+
private int beans;
41+
42+
public Jar(int beans, Lock lock) {
43+
this.beans = beans;
44+
this.lock = lock;
45+
}
46+
47+
/**
48+
* Method for a thief to take a bean.
49+
*/
50+
public boolean takeBean() {
51+
boolean success = false;
52+
try {
53+
lock.acquire();
54+
success = beans > 0;
55+
if (success) {
56+
beans = beans - 1;
57+
}
58+
} catch (Exception e) {
59+
e.printStackTrace();
60+
} finally {
61+
lock.release();
62+
}
63+
64+
return success;
65+
}
66+
67+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package com.iluwatar.mutex;
24+
25+
/**
26+
* Lock is an interface for a lock which can be acquired and released.
27+
*/
28+
public interface Lock {
29+
30+
void acquire() throws InterruptedException;
31+
32+
void release();
33+
34+
}
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package com.iluwatar.mutex;
24+
25+
/**
26+
* Mutex is an implementation of a mutual exclusion lock.
27+
*/
28+
public class Mutex implements Lock {
29+
30+
/**
31+
* The current owner of the lock.
32+
*/
33+
private Object owner;
34+
35+
/**
36+
* Returns the current owner of the Mutex, or null if available
37+
*/
38+
public Object getOwner() {
39+
return owner;
40+
}
41+
42+
/**
43+
* Method called by a thread to acquire the lock. If the lock has already
44+
* been acquired this will wait until the lock has been released to
45+
* re-attempt the acquire.
46+
*/
47+
@Override
48+
public synchronized void acquire() throws InterruptedException {
49+
while (owner != null) {
50+
wait();
51+
}
52+
53+
owner = Thread.currentThread();
54+
}
55+
56+
/**
57+
* Method called by a thread to release the lock.
58+
*/
59+
@Override
60+
public synchronized void release() {
61+
if (Thread.currentThread() == owner) {
62+
owner = null;
63+
notify();
64+
}
65+
}
66+
67+
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package com.iluwatar.mutex;
24+
25+
/**
26+
* Thief is a class which continually tries to acquire a jar and take a bean
27+
* from it. When the jar is empty the thief stops.
28+
*/
29+
public class Thief extends Thread {
30+
31+
/**
32+
* The name of the thief.
33+
*/
34+
private final String name;
35+
36+
/**
37+
* The jar
38+
*/
39+
private final Jar jar;
40+
41+
public Thief(String name, Jar jar) {
42+
this.name = name;
43+
this.jar = jar;
44+
}
45+
46+
/**
47+
* In the run method the thief repeatedly tries to take a bean until none
48+
* are left.
49+
*/
50+
@Override
51+
public void run() {
52+
int beans = 0;
53+
54+
while (jar.takeBean()) {
55+
beans = beans + 1;
56+
System.out.println(name + " took a bean.");
57+
}
58+
59+
System.out.println(name + " took " + beans + " beans.");
60+
}
61+
62+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* The MIT License
3+
* Copyright (c) 2014 Ilkka Seppälä
4+
*
5+
* Permission is hereby granted, free of charge, to any person obtaining a copy
6+
* of this software and associated documentation files (the "Software"), to deal
7+
* in the Software without restriction, including without limitation the rights
8+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
* copies of the Software, and to permit persons to whom the Software is
10+
* furnished to do so, subject to the following conditions:
11+
*
12+
* The above copyright notice and this permission notice shall be included in
13+
* all copies or substantial portions of the Software.
14+
*
15+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
* THE SOFTWARE.
22+
*/
23+
package com.iluwatar.mutex;
24+
25+
import org.junit.Test;
26+
import java.io.IOException;
27+
28+
public class AppTest{
29+
@Test
30+
public void test() throws IOException {
31+
String[] args = {};
32+
App.main(args);
33+
}
34+
}

0 commit comments

Comments
 (0)