KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jfun > yan > factory > SimplePool


1 package jfun.yan.factory;
2
3 /**
4  * A simple implementation of Pool that uses null
5  * to indicate non-existent pool entry.
6  * <p>
7  * This implementation synchronizes on {@link #getMutex()}
8  * for thread safety.
9  * </p>
10  * @author Ben Yu
11  * Feb 2, 2006 3:14:45 PM
12  */

13 public abstract class SimplePool<T> implements Pool<T> {
14   public T getInstance(Factory<T> factory) {
15     synchronized(getMutex()){
16       T ret = get();
17       if(ret==null){
18         ret = factory.create();
19         set(ret);
20       }
21       return ret;
22     }
23   }
24
25   public T getPooledInstance(T def) {
26     synchronized(getMutex()){
27       return ifnull(get(), def);
28     }
29   }
30   
31   public boolean isPooled() {
32     synchronized(getMutex()){
33       return get()!=null;
34     }
35   }
36   protected static <X> X ifnull(X obj, X def){
37     return obj==null?def:obj;
38   }
39   /**
40    * Get the pooled instance. null if not found.
41    * @return the pooled instance.
42    */

43   public abstract T get();
44   /**
45    * set an value to the pool.
46    * @param val the value to be pooled.
47    */

48   public abstract void set(T val);
49   
50   /**
51    * Get the object that can be used to synchronize.
52    */

53   protected abstract Object JavaDoc getMutex();
54 }
55
Popular Tags