Search code examples
javaapachepool

Class Cast Exception while adding Objects to Apache Pool


I'm trying to figure out how to implement Apache Pool 2 (I'm using 2.5). As an initial POC I created an Employee Object with firstName, lastName, employeeId and age (Observer Pattern). I created an EmployeeObjectFactory which implements PooledObjectFactory and in the main class I was trying to add objects of Employee class. But I'm getting a class cast exception(EmployeeObjects cannot be cast to PooledObjects). So what changes do I need to make to my EmployeeObjects?

Employee Class

public class Employee{
 private String firstName;
 // omitting the getters and setters for other fields

 public static class Builder {
  private String firstName = "Unsub";
  // declared and initialized lastName, emailId and age 
  public Builder firstName(String val) {
   firstName = val;
   return this;
  }
  // Similarly for other values
  public EmployeeObject build() {
   return new EmployeeObject(this);
  }
}

 private EmployeeObject(Builder builder) {
  firstName = builder.firstName;
  // omitting rest of the code
 }
}

In the EmployeeObjectFactory

public class EmployeeObjectFactory implements PooledObjectFactory<EmployeeObject> {

 @Override
 public PooledObject<EmployeeObject> makeObject() {
  return (PooledObject<EmployeeObject>) new EmployeeObject.Builder().build(); // This is where I'm getting the class cast
 }
 // Omitting rest of the code
}

Main Class

public static void main(String arg[]) throws Exception {
GenericObjectPool employeeObjectPool = new GenericObjectPool(new EmployeeObjectFactory());
employeeObjectPool.addObject(); 

I have tried to add as much little code as possible, because even I hate going through loads of code. Any help would be appreciated.


Solution

  • Finally got the answer after reading through the Apache Docs. DefaultPooledObject is what I need to use. DefaultPooledObject - "Create a new instance that wraps the provided object so that the pool can track the state of the pooled object." In the makeObject() function, I returned a DefaultPooledObject. So my code would look like

    @Override
    public PooledObject<EmployeeObject> makeObject() {
     return new DefaultPooledObject<>(new EmployeeObject.Builder().build());
    }