KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > repo > cache > ExpiringValueCache


1 /*
2  * Copyright (C) 2005 Alfresco, Inc.
3  *
4  * Licensed under the Mozilla Public License version 1.1
5  * with a permitted attribution clause. You may obtain a
6  * copy of the License at
7  *
8  * http://www.alfresco.org/legal/license.txt
9  *
10  * Unless required by applicable law or agreed to in writing,
11  * software distributed under the License is distributed on an
12  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13  * either express or implied. See the License for the specific
14  * language governing permissions and limitations under the
15  * License.
16  */

17 package org.alfresco.repo.cache;
18
19 /**
20  * Simple cache of a single Object value.
21  * <p>
22  * The object placed in the cache will automatically be discarded after a timeout value.
23  *
24  * @author Kevin Roast
25  */

26 public class ExpiringValueCache<T>
27 {
28     // default is to discard cached object after 1 minute
29
private final static long TIMEOUT_DEFAULT = 1000L*60L;
30     
31     private long timeout = TIMEOUT_DEFAULT;
32     private long snapshot = 0;
33     private T value;
34     
35     /**
36      * Default constructor.
37      *
38      * Uses the default timeout of 1 minute.
39      */

40     public ExpiringValueCache()
41     {
42     }
43     
44     /**
45      * Constructor
46      *
47      * @param timeout Timeout in milliseconds before cached value is discarded
48      */

49     public ExpiringValueCache(long timeout)
50     {
51         this.timeout = timeout;
52     }
53     
54     /**
55      * Put a value into the cache. The item will be return from the associated get() method
56      * until the timeout expires then null will be returned.
57      *
58      * @param value The object to store in the cache
59      */

60     public void put(T value)
61     {
62         this.value = value;
63         this.snapshot = System.currentTimeMillis();
64     }
65     
66     /**
67      * Get the cached object. The set item will be returned until it expires, then null will be returned.
68      *
69      * @return cached object or null if not set or expired.
70      */

71     public T get()
72     {
73         if (snapshot + timeout < System.currentTimeMillis())
74         {
75             this.value = null;
76         }
77         return this.value;
78     }
79     
80     /**
81      * Clear the cache value
82      */

83     public void clear()
84     {
85         this.value = null;
86     }
87 }
88
Popular Tags