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 33public 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}
Original file line number Diff line number Diff line change 11package com .iluwatar ;
22
3+ import java .util .HashSet ;
4+
35public 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}
Original file line number Diff line number Diff line change 11package com .iluwatar ;
22
33public 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}
You can’t perform that action at this time.
0 commit comments