Skip to content

Commit 07a77ba

Browse files
committed
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
1 parent 3c8b837 commit 07a77ba

File tree

2 files changed

+20
-12
lines changed

2 files changed

+20
-12
lines changed

double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/App.java

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.util.concurrent.ExecutorService;
44
import java.util.concurrent.Executors;
5+
import java.util.concurrent.TimeUnit;
56

67
/**
78
*
@@ -26,13 +27,17 @@ public static void main(String[] args) {
2627
final Inventory inventory = new Inventory(1000);
2728
ExecutorService executorService = Executors.newFixedThreadPool(3);
2829
for (int i = 0; i < 3; i++) {
29-
executorService.execute(new Runnable() {
30-
@Override
31-
public void run() {
32-
while (inventory.addItem(new Item()))
33-
;
34-
}
35-
});
30+
executorService.execute(() -> {
31+
while (inventory.addItem(new Item()))
32+
;
33+
});
34+
}
35+
36+
executorService.shutdown();
37+
try {
38+
executorService.awaitTermination(5, TimeUnit.SECONDS);
39+
} catch (InterruptedException e) {
40+
System.out.println("Error waiting for ExecutorService shutdown");
3641
}
3742
}
3843
}

double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking/Inventory.java

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,14 @@
1212
*/
1313
public class Inventory {
1414

15-
private int inventorySize;
16-
private List<Item> items;
17-
private Lock lock = new ReentrantLock();
15+
private final int inventorySize;
16+
private final List<Item> items;
17+
private final Lock lock;
1818

1919
public Inventory(int inventorySize) {
2020
this.inventorySize = inventorySize;
21-
this.items = new ArrayList<Item>(inventorySize);
21+
this.items = new ArrayList<>(inventorySize);
22+
this.lock = new ReentrantLock();
2223
}
2324

2425
public boolean addItem(Item item) {
@@ -27,7 +28,9 @@ public boolean addItem(Item item) {
2728
try {
2829
if (items.size() < inventorySize) {
2930
items.add(item);
30-
System.out.println(Thread.currentThread());
31+
System.out.println(Thread.currentThread()
32+
+ ": items.size()=" + items.size()
33+
+ ", inventorySize=" + inventorySize);
3134
return true;
3235
}
3336
} finally {

0 commit comments

Comments
 (0)