001: /*
002: * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved
003: *
004: * This file is part of Resin(R) Open Source
005: *
006: * Each copy or derived work must preserve the copyright notice and this
007: * notice unmodified.
008: *
009: * Resin Open Source is free software; you can redistribute it and/or modify
010: * it under the terms of the GNU General Public License as published by
011: * the Free Software Foundation; either version 2 of the License, or
012: * (at your option) any later version.
013: *
014: * Resin Open Source is distributed in the hope that it will be useful,
015: * but WITHOUT ANY WARRANTY; without even the implied warranty of
016: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
017: * of NON-INFRINGEMENT. See the GNU General Public License for more
018: * details.
019: *
020: * You should have received a copy of the GNU General Public License
021: * along with Resin Open Source; if not, write to the
022: * Free SoftwareFoundation, Inc.
023: * 59 Temple Place, Suite 330
024: * Boston, MA 02111-1307 USA
025: *
026: * @author Scott Ferguson
027: */
028:
029: package com.caucho.util;
030:
031: /**
032: * A single item timed cache. The item will remain valid until it expires.
033: * TimedItem can simplify database caching.
034: *
035: * <pre><code>
036: * TimedItem currentStories = new TimedItem(60000);
037: *
038: * public ArrayList getCurrentStories()
039: * {
040: * ArrayList storyList = (ArrayList) currentStories.get();
041: *
042: * if (storyList == null) {
043: * storyList = DB.queryStoryDatabase();
044: * currentStories.put(storyList);
045: * }
046: *
047: * return storyList;
048: * }
049: * </code></pre>
050: */
051: public class TimedItem {
052: private long expireInterval;
053:
054: private long createTime;
055: private Object value;
056:
057: /**
058: * Create a new timed item with a specified update time
059: *
060: * @param expireInterval the time in milliseconds the item remains valid.
061: */
062: public TimedItem(long expireInterval) {
063: this .expireInterval = expireInterval;
064: }
065:
066: /**
067: * Returns the expire time for this TimedItem.
068: */
069: public long getExpireInterval() {
070: return expireInterval;
071: }
072:
073: /**
074: * Sets the expire time for this timedItem.
075: */
076: public void setExpireInterval(long expireInterval) {
077: this .expireInterval = expireInterval;
078: }
079:
080: /**
081: * Sets the value.
082: */
083: public void put(Object value) {
084: createTime = Alarm.getCurrentTime();
085: this .value = value;
086: }
087:
088: /**
089: * Gets the cached value, returning null if expires.
090: */
091: public Object get() {
092: if (Alarm.getCurrentTime() < createTime + expireInterval)
093: return value;
094: else {
095: Object v = value;
096: value = null;
097:
098: if (v instanceof CacheListener)
099: ((CacheListener) v).removeEvent();
100:
101: return null;
102: }
103: }
104: }
|