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.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
*
|
*
|
||||||
@ -26,13 +27,17 @@ public class App {
|
|||||||
final Inventory inventory = new Inventory(1000);
|
final Inventory inventory = new Inventory(1000);
|
||||||
ExecutorService executorService = Executors.newFixedThreadPool(3);
|
ExecutorService executorService = Executors.newFixedThreadPool(3);
|
||||||
for (int i = 0; i < 3; i++) {
|
for (int i = 0; i < 3; i++) {
|
||||||
executorService.execute(new Runnable() {
|
executorService.execute(() -> {
|
||||||
@Override
|
while (inventory.addItem(new Item()))
|
||||||
public void run() {
|
;
|
||||||
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 {
|
public class Inventory {
|
||||||
|
|
||||||
private int inventorySize;
|
private final int inventorySize;
|
||||||
private List<Item> items;
|
private final List<Item> items;
|
||||||
private Lock lock = new ReentrantLock();
|
private final Lock lock;
|
||||||
|
|
||||||
public Inventory(int inventorySize) {
|
public Inventory(int inventorySize) {
|
||||||
this.inventorySize = inventorySize;
|
this.inventorySize = inventorySize;
|
||||||
this.items = new ArrayList<Item>(inventorySize);
|
this.items = new ArrayList<>(inventorySize);
|
||||||
|
this.lock = new ReentrantLock();
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean addItem(Item item) {
|
public boolean addItem(Item item) {
|
||||||
@ -27,7 +28,9 @@ public class Inventory {
|
|||||||
try {
|
try {
|
||||||
if (items.size() < inventorySize) {
|
if (items.size() < inventorySize) {
|
||||||
items.add(item);
|
items.add(item);
|
||||||
System.out.println(Thread.currentThread());
|
System.out.println(Thread.currentThread()
|
||||||
|
+ ": items.size()=" + items.size()
|
||||||
|
+ ", inventorySize=" + inventorySize);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user