Formatted all files to the same standard
This commit is contained in:
@ -4,7 +4,7 @@ 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
|
||||
@ -12,16 +12,17 @@ import java.util.concurrent.Executors;
|
||||
*/
|
||||
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()));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
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()))
|
||||
;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -5,9 +5,8 @@ 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();
|
||||
@ -16,17 +15,17 @@ public class Inventory {
|
||||
this.inventorySize = inventorySize;
|
||||
this.items = new ArrayList<Item>(inventorySize);
|
||||
}
|
||||
|
||||
public boolean addItem(Item item){
|
||||
if(items.size()<inventorySize){
|
||||
|
||||
public boolean addItem(Item item) {
|
||||
if (items.size() < inventorySize) {
|
||||
lock.lock();
|
||||
try{
|
||||
if(items.size()<inventorySize){
|
||||
try {
|
||||
if (items.size() < inventorySize) {
|
||||
items.add(item);
|
||||
System.out.println(Thread.currentThread());
|
||||
return true;
|
||||
}
|
||||
}finally{
|
||||
} finally {
|
||||
lock.unlock();
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user