Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 5. Pool > Object Factory Example

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 { }
}


					  


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial