2015-07-24 11:32:22 +03:00
|
|
|
package com.iluwatar.doublechecked.locking;
|
2014-09-07 00:34:26 +01:00
|
|
|
|
|
|
|
import java.util.concurrent.ExecutorService;
|
|
|
|
import java.util.concurrent.Executors;
|
2015-10-13 20:07:55 -05:00
|
|
|
import java.util.concurrent.TimeUnit;
|
2014-09-07 00:34:26 +01:00
|
|
|
|
|
|
|
/**
|
2014-10-08 13:42:12 +01:00
|
|
|
*
|
2015-11-01 21:29:13 -05:00
|
|
|
* Double Checked Locking is a concurrency design pattern used to reduce the overhead of acquiring a
|
|
|
|
* lock by first testing the locking criterion (the "lock hint") without actually acquiring the
|
|
|
|
* lock. Only if the locking criterion check indicates that locking is required does the actual
|
|
|
|
* locking logic proceed.
|
2015-10-03 21:00:21 +03:00
|
|
|
* <p>
|
2015-11-01 21:29:13 -05:00
|
|
|
* In {@link Inventory} we store the items with a given size. However, we do not store more items
|
|
|
|
* than the inventory size. To address concurrent access problems we use double checked locking to
|
|
|
|
* add item to inventory. In this method, the thread which gets the lock first adds the item.
|
2015-08-18 22:29:35 +03:00
|
|
|
*
|
2014-09-07 00:34:26 +01:00
|
|
|
*/
|
2014-10-07 16:23:37 +01:00
|
|
|
public class App {
|
2014-09-07 00:34:26 +01:00
|
|
|
|
2015-11-01 21:29:13 -05:00
|
|
|
/**
|
|
|
|
* Program entry point
|
|
|
|
*
|
|
|
|
* @param args command line args
|
|
|
|
*/
|
|
|
|
public static void main(String[] args) {
|
|
|
|
final Inventory inventory = new Inventory(1000);
|
|
|
|
ExecutorService executorService = Executors.newFixedThreadPool(3);
|
|
|
|
for (int i = 0; i < 3; i++) {
|
|
|
|
executorService.execute(() -> {
|
|
|
|
while (inventory.addItem(new Item()));
|
|
|
|
});
|
|
|
|
}
|
2015-10-13 20:07:55 -05:00
|
|
|
|
2015-11-01 21:29:13 -05:00
|
|
|
executorService.shutdown();
|
|
|
|
try {
|
|
|
|
executorService.awaitTermination(5, TimeUnit.SECONDS);
|
|
|
|
} catch (InterruptedException e) {
|
|
|
|
System.out.println("Error waiting for ExecutorService shutdown");
|
|
|
|
}
|
|
|
|
}
|
2014-09-07 00:34:26 +01:00
|
|
|
}
|