View Javadoc
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.pool2.performance;
19  
20  import org.apache.commons.pool2.PooledObject;
21  import org.apache.commons.pool2.PooledObjectFactory;
22  import org.apache.commons.pool2.Waiter;
23  import org.apache.commons.pool2.impl.DefaultPooledObject;
24  
25  /**
26   * Sleepy ObjectFactory (everything takes a while longer)
27   */
28  public class SleepingObjectFactory implements PooledObjectFactory<Integer> {
29  
30      private int counter;
31      private boolean debug;
32  
33      @Override
34      public void activateObject(final PooledObject<Integer> obj) {
35          debug("activateObject", obj);
36          Waiter.sleepQuietly(10);
37      }
38  
39      private void debug(final String method, final Object obj) {
40          if (debug) {
41              final String thread = "thread" + Thread.currentThread().getName();
42              System.out.println(thread + ": " + method + " " + obj);
43          }
44      }
45  
46      @Override
47      public void destroyObject(final PooledObject<Integer> obj) {
48          debug("destroyObject", obj);
49          Waiter.sleepQuietly(250);
50      }
51  
52      public boolean isDebug() {
53          return debug;
54      }
55  
56      @Override
57      public PooledObject<Integer> makeObject() {
58          // Deliberate choice to create a new object in case future unit tests
59          // check for a specific object.
60          final Integer obj = Integer.valueOf(counter++);
61          debug("makeObject", obj);
62          Waiter.sleepQuietly(500);
63          return new DefaultPooledObject<>(obj);
64      }
65  
66      @Override
67      public void passivateObject(final PooledObject<Integer> obj) {
68          debug("passivateObject", obj);
69          Waiter.sleepQuietly(10);
70      }
71  
72      public void setDebug(final boolean b) {
73          debug = b;
74      }
75  
76      @Override
77      public boolean validateObject(final PooledObject<Integer> obj) {
78          debug("validateObject", obj);
79          Waiter.sleepQuietly(30);
80          return true;
81      }
82  }