File tree Expand file tree Collapse file tree 2 files changed +20
-12
lines changed
double-checked-locking/src/main/java/com/iluwatar/doublechecked/locking Expand file tree Collapse file tree 2 files changed +20
-12
lines changed Original file line number Diff line number Diff line change 22
33import java .util .concurrent .ExecutorService ;
44import 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}
Original file line number Diff line number Diff line change 1212 */
1313public 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 {
You can’t perform that action at this time.
0 commit comments