01: package snaq.util;
02:
03: import java.util.*;
04:
05: /**
06: * Wrapper for an object, useful for providing caching/pooling support.
07: * @see snaq.util.CacheManager
08: * @see snaq.util.ObjectPool
09: * @author Giles Winstanley
10: */
11: public class TimeWrapper implements Cacheable {
12: private Object id, obj;
13: private long death = 0;
14: private long accessed = System.currentTimeMillis();
15:
16: /**
17: * Creates a new wrapped object.
18: * @param id identifier object
19: * @param obj object to be referenced
20: * @param expiryTime object's idle time before death in milliseconds (0 - eternal)
21: */
22: public TimeWrapper(Object id, Object obj, long expiryTime) {
23: this .id = id;
24: this .obj = obj;
25: if (expiryTime > 0)
26: this .death = System.currentTimeMillis() + expiryTime;
27: }
28:
29: /**
30: * Returns the object's identifier.
31: */
32: public Object getId() {
33: return id;
34: }
35:
36: /**
37: * Returns the object referenced by this wrapper.
38: */
39: public Object getObject() {
40: return obj;
41: }
42:
43: /**
44: * Sets idle time allowed before this item expires.
45: * @param expiryTime idle time before expiry (0 = eternal)
46: */
47: synchronized void setLiveTime(long expiryTime) {
48: if (expiryTime < 0)
49: throw new IllegalArgumentException("Invalid expiry time");
50: else if (expiryTime > 0)
51: this .death = System.currentTimeMillis() + expiryTime;
52: else
53: death = 0;
54: }
55:
56: /**
57: * Whether this item has expired.
58: * (Expiry of zero indicates that it will never expire)
59: */
60: public synchronized boolean isExpired() {
61: return death > 0 && System.currentTimeMillis() > death;
62: }
63:
64: /**
65: * Updates the time this object was last accessed.
66: */
67: synchronized void updateAccessed() {
68: accessed = System.currentTimeMillis();
69: }
70:
71: /**
72: * Returns the time this object was last accessed.
73: */
74: long getAccessed() {
75: return accessed;
76: }
77: }
|