001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.pool2;
018
019import java.io.PrintWriter;
020import java.time.Duration;
021import java.time.Instant;
022import java.util.Deque;
023
024/**
025 * Defines the wrapper that is used to track the additional information, such as
026 * state, for the pooled objects.
027 * <p>
028 * Implementations of this class are required to be thread-safe.
029 * </p>
030 *
031 * @param <T> the type of object in the pool.
032 * @since 2.0
033 */
034public interface PooledObject<T> extends Comparable<PooledObject<T>> {
035
036    /**
037     * Tests whether the given PooledObject is null <em>or</em> contains a null.
038     *
039     * @param pooledObject the PooledObject to test.
040     * @return whether the given PooledObject is null <em>or</em> contains a null.
041     * @since 2.12.0
042     */
043    static boolean isNull(final PooledObject<?> pooledObject) {
044        return pooledObject == null || pooledObject.getObject() == null;
045    }
046
047    /**
048     * Allocates the object.
049     *
050     * @return {@code true} if the original state was {@link PooledObjectState#IDLE IDLE}
051     */
052    boolean allocate();
053
054    /**
055     * Orders instances based on idle time - i.e. the length of time since the
056     * instance was returned to the pool. Used by the GKOP idle object evictor.
057     * <p>
058     * Note: This class has a natural ordering that is inconsistent with
059     *       equals if distinct objects have the same identity hash code.
060     * </p>
061     * <p>
062     * {@inheritDoc}
063     * </p>
064     */
065    @Override
066    int compareTo(PooledObject<T> other);
067
068    /**
069     * Deallocates the object and sets it {@link PooledObjectState#IDLE IDLE}
070     * if it is currently {@link PooledObjectState#ALLOCATED ALLOCATED}.
071     *
072     * @return {@code true} if the state was {@link PooledObjectState#ALLOCATED ALLOCATED}.
073     */
074    boolean deallocate();
075
076    /**
077     * Notifies the object that the eviction test has ended.
078     *
079     * @param idleQueue The queue of idle objects to which the object should be
080     *                  returned.
081     * @return  Currently not used.
082     */
083    boolean endEvictionTest(Deque<PooledObject<T>> idleQueue);
084
085    @Override
086    boolean equals(Object obj);
087
088    /**
089     * Gets the amount of time this object last spent in the active state (it may still be active in which case
090     * subsequent calls will return an increased value).
091     *
092     * @return The duration last spent in the active state.
093     * @since 2.11.0
094     */
095    default Duration getActiveDuration() {
096        // Take copies to avoid threading issues
097        final Instant lastReturnInstant = getLastReturnInstant();
098        final Instant lastBorrowInstant = getLastBorrowInstant();
099        // @formatter:off
100        return lastReturnInstant.isAfter(lastBorrowInstant) ?
101                Duration.between(lastBorrowInstant, lastReturnInstant) :
102                Duration.between(lastBorrowInstant, Instant.now());
103        // @formatter:on
104    }
105
106    /**
107     * Gets the amount of time this object last spent in the active state (it may still be active in which case
108     * subsequent calls will return an increased value).
109     *
110     * @return The duration last spent in the active state.
111     * @since 2.10.0
112     * @deprecated Use {@link #getActiveDuration()}.
113     */
114    @Deprecated
115    default Duration getActiveTime() {
116        return getActiveDuration();
117    }
118
119    /**
120     * Gets the amount of time in milliseconds this object last spent in the
121     * active state (it may still be active in which case subsequent calls will
122     * return an increased value).
123     *
124     * @return The time in milliseconds last spent in the active state.
125     * @deprecated Use {@link #getActiveTime()} which offers the best precision.
126     */
127    @Deprecated
128    long getActiveTimeMillis();
129
130    /**
131     * Gets the number of times this object has been borrowed.
132     *
133     * @return -1 by default for implementations prior to release 2.7.0.
134     * @since 2.7.0
135     */
136    default long getBorrowedCount() {
137        return -1;
138    }
139
140    /**
141     * Gets the time (using the same basis as {@link Instant#now()}) that this object was created.
142     *
143     * @return The creation time for the wrapped object.
144     * @since 2.11.0
145     */
146    default Instant getCreateInstant() {
147        return Instant.ofEpochMilli(getCreateTime());
148    }
149
150    /**
151     * Gets the time (using the same basis as
152     * {@link java.time.Clock#instant()}) that this object was created.
153     *
154     * @return The creation time for the wrapped object.
155     * @deprecated Use {@link #getCreateInstant()} which offers the best precision.
156     */
157    @Deprecated
158    long getCreateTime();
159
160    /**
161     * Gets the duration since this object was created (using {@link Instant#now()}).
162     *
163     * @return The duration since this object was created.
164     * @since 2.12.0
165     */
166    default Duration getFullDuration() {
167        return Duration.between(getCreateInstant(), Instant.now());
168    }
169
170    /**
171     * Gets the amount of time that this object last spend in the
172     * idle state (it may still be idle in which case subsequent calls will
173     * return an increased value).
174     *
175     * @return The amount of time in last spent in the idle state.
176     * @since 2.11.0
177     */
178    default Duration getIdleDuration() {
179        return Duration.ofMillis(getIdleTimeMillis());
180    }
181
182    /**
183     * Gets the amount of time that this object last spend in the
184     * idle state (it may still be idle in which case subsequent calls will
185     * return an increased value).
186     *
187     * @return The amount of time in last spent in the idle state.
188     * @since 2.10.0
189     * @deprecated Use {@link #getIdleDuration()}.
190     */
191    @Deprecated
192    default Duration getIdleTime() {
193        return Duration.ofMillis(getIdleTimeMillis());
194    }
195
196    /**
197     * Gets the amount of time in milliseconds that this object last spend in the
198     * idle state (it may still be idle in which case subsequent calls will
199     * return an increased value).
200     *
201     * @return The time in milliseconds last spent in the idle state.
202     * @deprecated Use {@link #getIdleTime()} which offers the best precision.
203     */
204    @Deprecated
205    long getIdleTimeMillis();
206
207    /**
208     * Gets the time the wrapped object was last borrowed.
209     *
210     * @return The time the object was last borrowed.
211     * @since 2.11.0
212     */
213    default Instant getLastBorrowInstant() {
214        return Instant.ofEpochMilli(getLastBorrowTime());
215    }
216
217    /**
218     * Gets the time the wrapped object was last borrowed.
219     *
220     * @return The time the object was last borrowed.
221     * @deprecated Use {@link #getLastBorrowInstant()} which offers the best precision.
222     */
223    @Deprecated
224    long getLastBorrowTime();
225
226    /**
227     * Gets the time the wrapped object was last borrowed.
228     *
229     * @return The time the object was last borrowed.
230     * @since 2.11.0
231     */
232    default Instant getLastReturnInstant() {
233        return Instant.ofEpochMilli(getLastReturnTime());
234    }
235
236    /**
237     * Gets the time the wrapped object was last returned.
238     *
239     * @return The time the object was last returned.
240     * @deprecated Use {@link #getLastReturnInstant()} which offers the best precision.
241     */
242    @Deprecated
243    long getLastReturnTime();
244
245    /**
246     * Gets an estimate of the last time this object was used. If the class of the pooled object implements
247     * {@link TrackedUse}, what is returned is the maximum of {@link TrackedUse#getLastUsedInstant()} and
248     * {@link #getLastBorrowTime()}; otherwise this method gives the same value as {@link #getLastBorrowTime()}.
249     *
250     * @return the last time this object was used
251     * @since 2.11.0
252     */
253    default Instant getLastUsedInstant() {
254        return Instant.ofEpochMilli(getLastUsedTime());
255    }
256
257    /**
258     * Gets an estimate of the last time this object was used.  If the class
259     * of the pooled object implements {@link TrackedUse}, what is returned is
260     * the maximum of {@link TrackedUse#getLastUsedInstant()} and
261     * {@link #getLastBorrowTime()}; otherwise this method gives the same
262     * value as {@link #getLastBorrowTime()}.
263     *
264     * @return the last time this object was used.
265     * @deprecated Use {@link #getLastUsedInstant()} which offers the best precision.
266     */
267    @Deprecated
268    long getLastUsedTime();
269
270    /**
271     * Gets the underlying object that is wrapped by this instance of
272     * {@link PooledObject}.
273     *
274     * @return The wrapped object.
275     */
276    T getObject();
277
278    /**
279     * Gets the state of this object.
280     *
281     * @return state
282     */
283    PooledObjectState getState();
284
285    @Override
286    int hashCode();
287
288    /**
289     * Sets the state to {@link PooledObjectState#INVALID INVALID}.
290     */
291    void invalidate();
292
293    /**
294     * Marks the pooled object as abandoned.
295     */
296    void markAbandoned();
297
298    /**
299     * Marks the object as returning to the pool.
300     */
301    void markReturning();
302
303    /**
304     * Prints the stack trace of the code that borrowed this pooled object and
305     * the stack trace of the last code to use this object (if available) to
306     * the supplied writer.
307     *
308     * @param   writer  The destination for the debug output.
309     */
310    void printStackTrace(PrintWriter writer);
311
312    /**
313     * Sets whether to use abandoned object tracking. If this is true the
314     * implementation will need to record the stack trace of the last caller to
315     * borrow this object.
316     *
317     * @param   logAbandoned    The new configuration setting for abandoned
318     *                          object tracking.
319     */
320    void setLogAbandoned(boolean logAbandoned);
321
322    /**
323     * Sets the stack trace generation strategy based on whether or not fully detailed stack traces are required.
324     * When set to false, abandoned logs may only include caller class information rather than method names, line
325     * numbers, and other normal metadata available in a full stack trace.
326     *
327     * @param requireFullStackTrace the new configuration setting for abandoned object logging.
328     * @since 2.7.0
329     */
330    default void setRequireFullStackTrace(final boolean requireFullStackTrace) {
331        // noop
332    }
333
334    /**
335     * Attempts to place the pooled object in the
336     * {@link PooledObjectState#EVICTION} state.
337     *
338     * @return {@code true} if the object was placed in the
339     *         {@link PooledObjectState#EVICTION} state otherwise
340     *         {@code false}.
341     */
342    boolean startEvictionTest();
343
344    /**
345     * Gets a String form of the wrapper for debug purposes. The format is
346     * not fixed and may change at any time.
347     *
348     * {@inheritDoc}
349     */
350    @Override
351    String toString();
352
353    /**
354     * Records the current stack trace as the last time the object was used.
355     */
356    void use();
357
358}