Merge pull request #265 from mkobit/double-checked-locking-executor-service-shutdown
Fix - Shutdown the ExecutorService in App so that the resources are c…
This commit is contained in:
commit
9cbc4a20b9
@ -2,6 +2,7 @@ package com.iluwatar.doublechecked.locking;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
*
|
||||
@ -26,13 +27,17 @@ public class App {
|
||||
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()))
|
||||
;
|
||||
}
|
||||
});
|
||||
executorService.execute(() -> {
|
||||
while (inventory.addItem(new Item()))
|
||||
;
|
||||
});
|
||||
}
|
||||
|
||||
executorService.shutdown();
|
||||
try {
|
||||
executorService.awaitTermination(5, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
System.out.println("Error waiting for ExecutorService shutdown");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -12,13 +12,14 @@ import java.util.concurrent.locks.ReentrantLock;
|
||||
*/
|
||||
public class Inventory {
|
||||
|
||||
private int inventorySize;
|
||||
private List<Item> items;
|
||||
private Lock lock = new ReentrantLock();
|
||||
private final int inventorySize;
|
||||
private final List<Item> items;
|
||||
private final Lock lock;
|
||||
|
||||
public Inventory(int inventorySize) {
|
||||
this.inventorySize = inventorySize;
|
||||
this.items = new ArrayList<Item>(inventorySize);
|
||||
this.items = new ArrayList<>(inventorySize);
|
||||
this.lock = new ReentrantLock();
|
||||
}
|
||||
|
||||
public boolean addItem(Item item) {
|
||||
@ -27,7 +28,9 @@ public class Inventory {
|
||||
try {
|
||||
if (items.size() < inventorySize) {
|
||||
items.add(item);
|
||||
System.out.println(Thread.currentThread());
|
||||
System.out.println(Thread.currentThread()
|
||||
+ ": items.size()=" + items.size()
|
||||
+ ", inventorySize=" + inventorySize);
|
||||
return true;
|
||||
}
|
||||
} finally {
|
||||
|
Loading…
x
Reference in New Issue
Block a user