KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > snaq > util > TimeWrapper


1 package snaq.util;
2
3 import java.util.*;
4
5 /**
6  * Wrapper for an object, useful for providing caching/pooling support.
7  * @see snaq.util.CacheManager
8  * @see snaq.util.ObjectPool
9  * @author Giles Winstanley
10  */

11 public class TimeWrapper implements Cacheable
12 {
13     private Object JavaDoc id, obj;
14     private long death = 0;
15     private long accessed = System.currentTimeMillis();
16
17     /**
18      * Creates a new wrapped object.
19      * @param id identifier object
20      * @param obj object to be referenced
21      * @param expiryTime object's idle time before death in milliseconds (0 - eternal)
22      */

23     public TimeWrapper(Object JavaDoc id, Object JavaDoc obj, long expiryTime)
24     {
25         this.id = id;
26         this.obj = obj;
27         if (expiryTime > 0)
28             this.death = System.currentTimeMillis() + expiryTime;
29     }
30
31     /**
32      * Returns the object's identifier.
33      */

34     public Object JavaDoc getId()
35     {
36         return id;
37     }
38
39     /**
40      * Returns the object referenced by this wrapper.
41      */

42     public Object JavaDoc getObject() { return obj; }
43
44     /**
45      * Sets idle time allowed before this item expires.
46      * @param expiryTime idle time before expiry (0 = eternal)
47      */

48     synchronized void setLiveTime(long expiryTime)
49     {
50         if (expiryTime < 0)
51             throw new IllegalArgumentException JavaDoc("Invalid expiry time");
52         else if (expiryTime > 0)
53             this.death = System.currentTimeMillis() + expiryTime;
54         else
55             death = 0;
56     }
57
58     /**
59      * Whether this item has expired.
60      * (Expiry of zero indicates that it will never expire)
61      */

62     public synchronized boolean isExpired()
63     {
64         return death > 0 && System.currentTimeMillis() > death;
65     }
66
67     /**
68      * Updates the time this object was last accessed.
69      */

70     synchronized void updateAccessed() { accessed = System.currentTimeMillis(); }
71
72     /**
73      * Returns the time this object was last accessed.
74      */

75     long getAccessed() { return accessed; }
76 }
Popular Tags