1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    * 
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   * 
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.pool.performance;
19  
20  import org.apache.commons.pool.PoolableObjectFactory;
21  
22  /**
23   * Sleepy ObjectFactory (everything takes a while longer)
24   * 
25   * @author Dirk Verbeeck
26   * @version $Revision: 777749 $ $Date: 2009-05-22 20:04:54 -0400 (Fri, 22 May 2009) $ 
27   */
28  public class SleepingObjectFactory implements PoolableObjectFactory {
29  
30      private int counter = 0;
31      private boolean debug = false;
32  
33      public Object makeObject() throws Exception {
34          Object obj = new Integer(counter++);
35          debug("makeObject", obj);
36          sleep(500);
37          return obj;
38      }
39  
40      public void destroyObject(Object obj) throws Exception {
41          debug("destroyObject", obj);
42          sleep(250);
43      }
44  
45      public boolean validateObject(Object obj) {
46          debug("validateObject", obj);
47          sleep(30);
48          return true;
49      }
50  
51      public void activateObject(Object obj) throws Exception {
52          debug("activateObject", obj);
53          sleep(10);
54      }
55  
56      public void passivateObject(Object obj) throws Exception {
57          debug("passivateObject", obj);
58          sleep(10);
59      }
60      
61      private void debug(String method, Object obj) {
62          if (debug) {
63              String thread = "thread" + Thread.currentThread().getName();
64              System.out.println(thread + ": " + method + " " + obj);
65          }
66      }
67      
68      private void sleep(long millis) {
69          try {
70              Thread.sleep(millis);
71          }
72          catch (InterruptedException e) {
73          }
74      }
75  
76      public boolean isDebug() {
77          return debug;
78      }
79  
80      public void setDebug(boolean b) {
81          debug = b;
82      }
83  }