File tree Expand file tree Collapse file tree 5 files changed +81
-0
lines changed
src/main/java/com/iluwatar Expand file tree Collapse file tree 5 files changed +81
-0
lines changed Original file line number Diff line number Diff line change 1+ <project xmlns =" http://maven.apache.org/POM/4.0.0" xmlns : xsi =" http://www.w3.org/2001/XMLSchema-instance" xsi : schemaLocation =" http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
2+ <modelVersion >4.0.0</modelVersion >
3+ <parent >
4+ <groupId >com.iluwatar</groupId >
5+ <artifactId >java-design-patterns</artifactId >
6+ <version >1.0-SNAPSHOT</version >
7+ </parent >
8+ <artifactId >double-checked-locking</artifactId >
9+ </project >
Original file line number Diff line number Diff line change 1+ package com .iluwatar ;
2+
3+ import java .util .concurrent .ExecutorService ;
4+ import java .util .concurrent .Executors ;
5+
6+ /**
7+ *
8+ * In Inventory we store the items with a given size. However,
9+ * we do not store more items than the inventory size. To address
10+ * concurrent access problems we use double checked locking to add
11+ * item to inventory. In this method, the thread which gets the lock
12+ * first adds the item.
13+ */
14+
15+ public class App
16+ {
17+ public static void main ( String [] args )
18+ {
19+ final Inventory inventory = new Inventory (1000 );
20+ ExecutorService executorService = Executors .newFixedThreadPool (3 );
21+ for (int i = 0 ; i < 3 ; i ++) {
22+ executorService .execute (new Runnable () {
23+ @ Override
24+ public void run () {
25+ while (inventory .addItem (new Item ()));
26+ }
27+ });
28+ }
29+ }
30+ }
Original file line number Diff line number Diff line change 1+ package com .iluwatar ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+ import java .util .concurrent .locks .Lock ;
6+ import java .util .concurrent .locks .ReentrantLock ;
7+
8+
9+ public class Inventory {
10+
11+ private int inventorySize ;
12+ private List <Item > items ;
13+ private Lock lock = new ReentrantLock ();
14+
15+ public Inventory (int inventorySize ) {
16+ this .inventorySize = inventorySize ;
17+ this .items = new ArrayList <Item >(inventorySize );
18+ }
19+
20+ public boolean addItem (Item item ){
21+ if (items .size ()<inventorySize ){
22+ lock .lock ();
23+ try {
24+ if (items .size ()<inventorySize ){
25+ items .add (item );
26+ System .out .println (Thread .currentThread ());
27+ return true ;
28+ }
29+ }finally {
30+ lock .unlock ();
31+ }
32+ }
33+ return false ;
34+ }
35+
36+ }
Original file line number Diff line number Diff line change 1+ package com .iluwatar ;
2+
3+ public class Item {
4+
5+ }
Original file line number Diff line number Diff line change 4141 <module >strategy</module >
4242 <module >template-method</module >
4343 <module >visitor</module >
44+ <module >double-checked-locking</module >
4445 </modules >
4546
4647<build >
You can’t perform that action at this time.
0 commit comments