Object Factory Example


The object factory, shown in Listing 5-2, implements the PoolableObjectFactory interface. The two key methods implemented are makeObject() and validateObject(). The factory always returns false for an invalid object because when a thread enters a finished state, it cannot be reused. Because the pool is configured to always test on return (as shown in Listing 5-1), this means that the WorkerThread will be removed when completed.

Listing 5-2. Thread Factory
 package com.cascadetg.ch05; import org.apache.commons.pool.PoolableObjectFactory; public class WorkerThreadFactory implements PoolableObjectFactory {     /** Keeps track of the currently created thread. */     public int currentThread = 0;     /**  Create and name the thread.  Naming the thread is very      * helpful when trying to debug multi-threaded applications.      */     public Object makeObject() throws Exception     {         WorkerThread temp = new WorkerThread();         temp.setName("Worker Thread #" + currentThread++);         return temp;     }     /** We aren't reusing threads, so we always return false here,      * causing the pool to remove this thread from the pool and      * create a new object using the makeObject() method.      */     public boolean validateObject(Object arg0) { return false; }     public void destroyObject(Object arg0) throws Exception  { }     public void activateObject(Object arg0) throws Exception { }     public void passivateObject(Object arg0) throws Exception { } } 



    Apache Jakarta Commons(c) Reusable Java Components
    Real World Web Services
    ISBN: N/A
    EAN: 2147483647
    Year: 2006
    Pages: 137
    Authors: Will Iverson

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net