Fix - Shutdown the ExecutorService in App so that the resources are collected and the process can finish
I ran App.main(String[] args) in the 'double-checked-locking' module and the process does not terminate. This is because the executor service still has open threads. I'm not sure how the JUnit tests are run, but it seems they are handling the leftover resources themselves. Also, minor modifications to Inventory for final fields are used since there is no state change around them, and added some more meaningful printing so the example is more clearly demonstrated
This commit is contained in:
parent
3c8b83748a
commit
07a77ba11d
@ -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