From f2f1d8e62f0ca94e7dafdaac1e8012efe2d11e74 Mon Sep 17 00:00:00 2001 From: mdb Date: Sat, 20 May 2006 22:36:17 +0000 Subject: [PATCH] Added a handy class for caching things for a spell. git-svn-id: https://samskivert.googlecode.com/svn/trunk@1846 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- .../samskivert/util/ExpiringReference.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/java/com/samskivert/util/ExpiringReference.java diff --git a/src/java/com/samskivert/util/ExpiringReference.java b/src/java/com/samskivert/util/ExpiringReference.java new file mode 100644 index 00000000..22ba0017 --- /dev/null +++ b/src/java/com/samskivert/util/ExpiringReference.java @@ -0,0 +1,61 @@ +// +// samskivert library - useful routines for java programs +// Copyright (C) 2001-2006 Michael Bayne +// +// This library is free software; you can redistribute it and/or modify it +// under the terms of the GNU Lesser General Public License as published +// by the Free Software Foundation; either version 2.1 of the License, or +// (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +package com.samskivert.util; + +/** + * Provides a simple way of tracking a resource that should become stale after + * a certain time period. This is useful for caching data that was expensive to + * compute and should be cached for some time before being recreated. + * + *

Note: the data will not be unreferenced and thus garbage + * collectable until it has been requested at least once after it has expired. + * Thus expiring references must be combined with an {@link LRUHashMap} if + * memory conservation is also desired. + */ +public class ExpiringReference +{ + /** + * Creates an reference to the specified value that will expire in the + * specified number of milliseconds. + */ + public ExpiringReference (T value, long expireMillis) + { + _value = value; + _expires = System.currentTimeMillis() + expireMillis; + } + + /** + * Returns the value with which we were created or null if the value has + * expired. + */ + public T getValue () + { + if (_value == null) { + return null; + } else if (System.currentTimeMillis() >= _expires) { + _value = null; + return null; + } else { + return _value; + } + } + + protected T _value; + protected long _expires; +}