View Javadoc

1   /*
2    * Copyright (c) 2005, The K-Wf Grid Consortium
3    * Fraunhofer Institute for Computer Architecture and Software Technology
4    * See http://www.kwfgrid.eu and http://www.first.fraunhofer.de for more details.
5    */
6   package net.kwfgrid.gworkflowdl.protocol.util;
7   
8   import java.util.*;
9   
10  /***
11     Main class for an object pool.
12     It can be subclassed to pool certain types of objects.
13     The object pool manages a certain number of object instances and makes
14     them available to clients in a thread-safe manner. 
15   */
16  public abstract class ObjectPool {
17      private Collection _pool;
18      private Collection _inuse;
19  
20      protected ObjectPool(int size) {
21  	_pool = new HashSet(size);
22  	_inuse = new HashSet(size);
23  	for (int i=0; i<size; i++) {
24  	    _pool.add(createObject());
25  	}
26      }
27  
28      protected abstract Object createObject();
29  
30      /***
31         Get an object from the pool.
32         This method will block until an object is available.
33         @return A object from this object pool.
34         @exception InterruptedException If the thread was interrupted while waiting for an object to be available.
35       */
36      public synchronized Object getObject() throws InterruptedException {
37  	while (_pool.isEmpty()) wait();
38  	Object o = _pool.iterator().next();
39  	_pool.remove(o);
40  	_inuse.add(o);
41  	return o;
42      }
43  
44      /***
45         Return an object to the pool.
46         If the specified object has not been retrieved form this pool,
47         nothing happens. Otherwise the specified object will be made available again and can
48         be retrieved by other threads by calling <code>getObject</code>.
49         The object must not be utilized after it has been returned to the pool.
50         @param o The object to return to the pool.
51       */
52      public synchronized void returnObject(Object o) {
53  	if (_inuse.remove(o)) {
54  	    _pool.add(o);
55  	    notifyAll();
56  	}
57      }
58  }