Finished example.

This commit is contained in:
Ilkka Seppälä 2015-05-24 21:47:57 +03:00
parent 9122c7f0e6
commit bff34cfd21
3 changed files with 56 additions and 3 deletions

View File

@ -3,5 +3,25 @@ package com.iluwatar;
public class App {
public static void main( String[] args ) {
OliphauntPool pool = new OliphauntPool();
System.out.println(pool);
Oliphaunt oliphaunt1 = pool.checkOut();
System.out.println("Checked out " + oliphaunt1);
System.out.println(pool);
Oliphaunt oliphaunt2 = pool.checkOut();
System.out.println("Checked out " + oliphaunt2);
Oliphaunt oliphaunt3 = pool.checkOut();
System.out.println("Checked out " + oliphaunt3);
System.out.println(pool);
System.out.println("Checking in " + oliphaunt1);
pool.checkIn(oliphaunt1);
System.out.println("Checking in " + oliphaunt2);
pool.checkIn(oliphaunt2);
System.out.println(pool);
Oliphaunt oliphaunt4 = pool.checkOut();
System.out.println("Checked out " + oliphaunt4);
Oliphaunt oliphaunt5 = pool.checkOut();
System.out.println("Checked out " + oliphaunt5);
System.out.println(pool);
}
}

View File

@ -1,14 +1,31 @@
package com.iluwatar;
import java.util.HashSet;
public abstract class ObjectPool<T> {
HashSet<T> available = new HashSet<>();
HashSet<T> inUse = new HashSet<>();
protected abstract T create();
public synchronized T checkOut() {
return null;
if (available.size() <= 0) {
available.add(create());
}
T instance = available.iterator().next();
available.remove(instance);
inUse.add(instance);
return instance;
}
public synchronized void checkIn(T instance) {
inUse.remove(instance);
available.add(instance);
}
@Override
public String toString() {
return String.format("Pool available=%d inUse=%d", available.size(), inUse.size());
}
}

View File

@ -1,5 +1,21 @@
package com.iluwatar;
public class Oliphaunt {
private static int counter = 1;
private final int id;
public Oliphaunt() {
id = counter++;
}
public int getId() {
return id;
}
@Override
public String toString() {
return String.format("Oliphaunt id=%d", id);
}
}