double-checked-locking pattern is added.
This commit is contained in:
parent
0509e48d37
commit
1f0bedbbe1
9
double-checked-locking/pom.xml
Normal file
9
double-checked-locking/pom.xml
Normal file
@ -0,0 +1,9 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.iluwatar</groupId>
|
||||
<artifactId>java-design-patterns</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>double-checked-locking</artifactId>
|
||||
</project>
|
30
double-checked-locking/src/main/java/com/iluwatar/App.java
Normal file
30
double-checked-locking/src/main/java/com/iluwatar/App.java
Normal file
@ -0,0 +1,30 @@
|
||||
package com.iluwatar;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
*
|
||||
* In Inventory we store the items with a given size. However,
|
||||
* we do not store more items than the inventory size. To address
|
||||
* concurrent access problems we use double checked locking to add
|
||||
* item to inventory. In this method, the thread which gets the lock
|
||||
* first adds the item.
|
||||
*/
|
||||
|
||||
public class App
|
||||
{
|
||||
public static void main( String[] args )
|
||||
{
|
||||
final Inventory inventory = new Inventory(1000);
|
||||
ExecutorService executorService = Executors.newFixedThreadPool(3);
|
||||
for (int i = 0; i < 3; i++) {
|
||||
executorService.execute(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
while(inventory.addItem(new Item()));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,36 @@
|
||||
package com.iluwatar;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.locks.Lock;
|
||||
import java.util.concurrent.locks.ReentrantLock;
|
||||
|
||||
|
||||
public class Inventory {
|
||||
|
||||
private int inventorySize;
|
||||
private List<Item> items;
|
||||
private Lock lock = new ReentrantLock();
|
||||
|
||||
public Inventory(int inventorySize) {
|
||||
this.inventorySize = inventorySize;
|
||||
this.items = new ArrayList<Item>(inventorySize);
|
||||
}
|
||||
|
||||
public boolean addItem(Item item){
|
||||
if(items.size()<inventorySize){
|
||||
lock.lock();
|
||||
try{
|
||||
if(items.size()<inventorySize){
|
||||
items.add(item);
|
||||
System.out.println(Thread.currentThread());
|
||||
return true;
|
||||
}
|
||||
}finally{
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,5 @@
|
||||
package com.iluwatar;
|
||||
|
||||
public class Item {
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user