forked from iluwatar/java-design-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInventory.java
More file actions
35 lines (29 loc) · 720 Bytes
/
Copy pathInventory.java
File metadata and controls
35 lines (29 loc) · 720 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.iluwatar;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Inventory {
private int inventorySize;
private List<Item> items;
private Lock lock = new ReentrantLock();
public Inventory(int inventorySize) {
this.inventorySize = inventorySize;
this.items = new ArrayList<Item>(inventorySize);
}
public boolean addItem(Item item) {
if (items.size() < inventorySize) {
lock.lock();
try {
if (items.size() < inventorySize) {
items.add(item);
System.out.println(Thread.currentThread());
return true;
}
} finally {
lock.unlock();
}
}
return false;
}
}