File tree Expand file tree Collapse file tree 3 files changed +56
-3
lines changed
object-pool/src/main/java/com/iluwatar Expand file tree Collapse file tree 3 files changed +56
-3
lines changed Original file line number Diff line number Diff line change 3
3
public class App {
4
4
5
5
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 );
6
26
}
7
27
}
Original file line number Diff line number Diff line change 1
1
package com .iluwatar ;
2
2
3
+ import java .util .HashSet ;
4
+
3
5
public abstract class ObjectPool <T > {
4
6
7
+ HashSet <T > available = new HashSet <>();
8
+ HashSet <T > inUse = new HashSet <>();
9
+
5
10
protected abstract T create ();
6
11
7
12
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 ;
9
20
}
10
21
11
22
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 ());
13
30
}
14
31
}
Original file line number Diff line number Diff line change 1
1
package com .iluwatar ;
2
2
3
3
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
+ }
5
21
}
You can’t perform that action at this time.
0 commit comments