diff --git a/double-checked-locking/pom.xml b/double-checked-locking/pom.xml new file mode 100644 index 000000000..5bb7c486b --- /dev/null +++ b/double-checked-locking/pom.xml @@ -0,0 +1,9 @@ + + 4.0.0 + + com.iluwatar + java-design-patterns + 1.0-SNAPSHOT + + double-checked-locking + \ No newline at end of file diff --git a/double-checked-locking/src/main/java/com/iluwatar/App.java b/double-checked-locking/src/main/java/com/iluwatar/App.java new file mode 100644 index 000000000..7e6bfd532 --- /dev/null +++ b/double-checked-locking/src/main/java/com/iluwatar/App.java @@ -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())); + } + }); + } + } +} diff --git a/double-checked-locking/src/main/java/com/iluwatar/Inventory.java b/double-checked-locking/src/main/java/com/iluwatar/Inventory.java new file mode 100644 index 000000000..a6ddc350d --- /dev/null +++ b/double-checked-locking/src/main/java/com/iluwatar/Inventory.java @@ -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 items; + private Lock lock = new ReentrantLock(); + + public Inventory(int inventorySize) { + this.inventorySize = inventorySize; + this.items = new ArrayList(inventorySize); + } + + public boolean addItem(Item item){ + if(items.size()strategy template-method visitor + double-checked-locking