Skip to content

Commit bff34cf

Browse files
committed
Finished example.
1 parent 9122c7f commit bff34cf

File tree

3 files changed

+56
-3
lines changed

3 files changed

+56
-3
lines changed

object-pool/src/main/java/com/iluwatar/App.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,25 @@
33
public class App {
44

55
public static void main( String[] args ) {
6+
OliphauntPool pool = new OliphauntPool();
7+
System.out.println(pool);
8+
Oliphaunt oliphaunt1 = pool.checkOut();
9+
System.out.println("Checked out " + oliphaunt1);
10+
System.out.println(pool);
11+
Oliphaunt oliphaunt2 = pool.checkOut();
12+
System.out.println("Checked out " + oliphaunt2);
13+
Oliphaunt oliphaunt3 = pool.checkOut();
14+
System.out.println("Checked out " + oliphaunt3);
15+
System.out.println(pool);
16+
System.out.println("Checking in " + oliphaunt1);
17+
pool.checkIn(oliphaunt1);
18+
System.out.println("Checking in " + oliphaunt2);
19+
pool.checkIn(oliphaunt2);
20+
System.out.println(pool);
21+
Oliphaunt oliphaunt4 = pool.checkOut();
22+
System.out.println("Checked out " + oliphaunt4);
23+
Oliphaunt oliphaunt5 = pool.checkOut();
24+
System.out.println("Checked out " + oliphaunt5);
25+
System.out.println(pool);
626
}
727
}
Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,31 @@
11
package com.iluwatar;
22

3+
import java.util.HashSet;
4+
35
public abstract class ObjectPool<T> {
46

7+
HashSet<T> available = new HashSet<>();
8+
HashSet<T> inUse = new HashSet<>();
9+
510
protected abstract T create();
611

712
public synchronized T checkOut() {
8-
return null;
13+
if (available.size() <= 0) {
14+
available.add(create());
15+
}
16+
T instance = available.iterator().next();
17+
available.remove(instance);
18+
inUse.add(instance);
19+
return instance;
920
}
1021

1122
public synchronized void checkIn(T instance) {
12-
23+
inUse.remove(instance);
24+
available.add(instance);
25+
}
26+
27+
@Override
28+
public String toString() {
29+
return String.format("Pool available=%d inUse=%d", available.size(), inUse.size());
1330
}
1431
}
Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,21 @@
11
package com.iluwatar;
22

33
public class Oliphaunt {
4-
4+
5+
private static int counter = 1;
6+
7+
private final int id;
8+
9+
public Oliphaunt() {
10+
id = counter++;
11+
}
12+
13+
public int getId() {
14+
return id;
15+
}
16+
17+
@Override
18+
public String toString() {
19+
return String.format("Oliphaunt id=%d", id);
20+
}
521
}

0 commit comments

Comments
 (0)