#108 Consistent package naming throughout the examples

This commit is contained in:
Ilkka Seppala
2015-07-24 11:32:22 +03:00
parent af92d8dde5
commit 3d488ec15a
128 changed files with 963 additions and 873 deletions

View File

@@ -0,0 +1,28 @@
package com.iluwatar.doublechecked.locking;
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()))
;
}
});
}
}
}

View File

@@ -0,0 +1,35 @@
package com.iluwatar.doublechecked.locking;
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;
}
}

View File

@@ -0,0 +1,6 @@
package com.iluwatar.doublechecked.locking;
public class Item {
String name;
int level;
}