Skip to content

Instantly share code, notes, and snippets.

@Magnum97
Last active May 28, 2021 05:23
Show Gist options
  • Save Magnum97/d5578647e676e580e25b8960bcbc8ebd to your computer and use it in GitHub Desktop.
Save Magnum97/d5578647e676e580e25b8960bcbc8ebd to your computer and use it in GitHub Desktop.
Auto expire object cache
import java.util.Calendar;
import java.util.Date;
/**
* Title: Caching
Description: This interface defines the methods, which must be implemented
by
all objects wishing to be placed in the cache.
*
* Copyright: Copyright (c) 2001
* Company: JavaWorld
* FileName: Cacheable.java
@author Jonathan Lurie
@version 1.0
*/
public interface Cacheable
{
/* By requiring all objects to determine their own expirations, the
algorithm is abstracted from the caching service, thereby providing maximum
flexibility since each object can adopt a different expiration strategy.
*/
public boolean isExpired();
/* This method will ensure that the caching service is not responsible for
uniquely identifying objects placed in the cache.
*/
public Object getIdentifier();
}
import java.util.Calendar;
import java.util.Date;
public class CachedObject implements Cacheable {
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/* This variable will be used to determine if the object is expired.
*/
private Date dateOfExpiration = null;
private Object identifier = null;
/* This contains the real "value". This is the object which needs to be
shared.
*/
public Object object = null;
// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public CachedObject(Object obj, Object id, int minutesToLive) {
this.object = obj;
this.identifier = id;
if (minutesToLive != 0) {
dateOfExpiration = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(dateOfExpiration);
cal.add(cal.MINUTE, minutesToLive);
dateOfExpiration = cal.getTime();
}
}
public boolean isExpired() {
if (dateOfExpiration != null) {
if (dateOfExpiration.before(new Date())) {
System.out.println("CachedResultSet.isExpired: " +
"True Expire Time: " + dateOfExpiration.toString() +
"Current time: " + new Date().toString());
return true;
} else {
System.out.println("CachedResultSet.isExpired: False");
return false;
}
} else
return false;
}
public Object getIdentifier() {
return identifier;
}
}
import java.util.HashMap;
import java.util.Set;
public class CacheManager {
/* This is the HashMap that contains all objects in the cache. */
private static HashMap cacheHashMap = new HashMap();
/* This object acts as a semaphore, which protects the HashMap */
/* RESERVED FOR FUTURE USE private static Object lock = new Object(); */
static {
try {
/* Create background thread, which will be responsible for purging expired items. */
Thread threadCleanerUpper = new Thread(
new Runnable() {
/* The default time the thread should sleep between scans.
* The sleep method takes in a millisecond value so 5000 = 5
* Seconds.
*/
final int milliSecondsSleepTime = 5000;
public void run() {
try {
while (true) {
System.out.println("ThreadCleanerUpper Scanning for expired objects...");
/* Get the set of all keys that are in cache. These are the unique identifiers */
Set keySet = cacheHashMap.keySet();
for (Object key : keySet) {
/* Get the individual key. We need to hold on to this key in case it needs to be removed */
Cacheable value = (Cacheable) cacheHashMap.get(key);
if (value.isExpired()) {
cacheHashMap.remove(key);
System.out.println("ThreadCleanerUpper found expired object");
}
}
Thread.sleep(milliSecondsSleepTime);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
threadCleanerUpper.setPriority(Thread.MIN_PRIORITY);
threadCleanerUpper.start();
} catch (Exception e) {
System.out.println("CacheManager.Static Block: " + e);
}
}
public CacheManager() {
}
public static void putCache(Cacheable object) {
cacheHashMap.put(object.getIdentifier(), object);
}
public static Cacheable getCache(Object identifier) {
Cacheable object = (Cacheable) cacheHashMap.get(identifier);
if (object == null)
return null;
if (object.isExpired()) {
cacheHashMap.remove(identifier);
return null;
} else {
return object;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment