⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cache.java

📁 一个用struts tiles的在线影院web系统
💻 JAVA
字号:
package com.eline.vod.utils.caching;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

/**
 * Title: Runtime Cache test version....
 * Update: 2006-05-25
 * @author Lucifer
 *
 */
public class Cache {

	private class CachedObject {
		/*
		 * This variable will be used to determine if the object is expired.
		 */
		private Date absoluteExpiration = null;
		private int slidingExpiration = 0;
		
		private String key = null;
		
		/*
		 * This contains the real "value". This is the object which needs to be
		 * shared.
		 */
		public Object value = null;

		public CachedObject(String key, Object value, Date absoluteExpiration, int slidingExpiration) {
			this.key = key;
			this.value = value;

			this.absoluteExpiration = absoluteExpiration;
			this.slidingExpiration = slidingExpiration;
			
			if (slidingExpiration != 0) {
				if (absoluteExpiration == null)
					this.absoluteExpiration = new Date();

				/* Adjust date of expiration. */
				Calendar cal = Calendar.getInstance();
				cal.setTime(this.absoluteExpiration);
				cal.add(Calendar.MINUTE, slidingExpiration);
				this.absoluteExpiration = cal.getTime();
			}
		}
		
		public boolean isExpired() {
			/* Date of expiration is compared. */
			if (absoluteExpiration.before(new Date())) {
				//AppLogger.debug("CachedObject Expired from Cache! EXPIRE TIME: "
				//		+ absoluteExpiration.toString()
				//		+ " CURRENT TIME: " + (new Date()).toString());
				return true;
			} else {
				//AppLogger.debug("CachedObject Expired not from Cache!");
				return false;
			}
		}
		
		public void updateExpiration() {
			Calendar cal = Calendar.getInstance();
			cal.setTime(this.absoluteExpiration);
			cal.add(Calendar.MINUTE, slidingExpiration);
			this.absoluteExpiration = cal.getTime();
		}

		public String getKey() {
			return key;
		}

		public Object getValue() {
			return value;
		}

		public void setValue(Object value) {
			this.value = value;
		}
	};

	/* This is the HashMap that contains all objects in the cache. */
	private HashMap cacheHashMap = new HashMap();

	public static final Date NoAbsoluteExpiration = new Date(0x7fffffff)	;
	public static final int NoSlidingExpiration = 0;

	private static Cache instance = null;
	
	public static Cache getInstance() {
		if (instance == null)
			instance = new Cache();
		return instance;
	}

	private Cache() {
    	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 30000 = 30
				 * Seconds.
				 */
				static final int milliSecondSleepTime = 30000;

				public void run() {
					try {
						/*
						 * Sets up an infinite loop. The thread will continue
						 * looping forever.
						 */
						while (true) {
							//AppLogger.debug("Scanning For Expired Objects...:count:" + cacheHashMap.size());

							/*
							 * Get the set of all keys that are in cache. These
							 * are the unique identifiers
							 */
							Set keySet = cacheHashMap.keySet();

							/* An iterator is used to move through the Keyset */
							Iterator keys = keySet.iterator();

							/*
							 * Sets up a loop that will iterate through each key
							 * in the KeySet
							 */
							ArrayList keyToRemove = new ArrayList();
							while (keys.hasNext()) {
								/*
								 * Get the individual key. We need to hold on to
								 * this key in case it needs to be removed
								 */
								Object key = keys.next();

								/*
								 * Get the cacheable object associated with the
								 * key inside the cache
								 */
								CachedObject value = (CachedObject) cacheHashMap.get(key);

								/* Is the cacheable object expired? */
								if (value.isExpired()) {
									/*
									 * Yes it's expired! Remove it from the
									 * cache
									 */
									// cacheHashMap.remove(key);
									keyToRemove.add(key);
									//AppLogger.debug("Running.... Found an Expired Object in the Cache.");
								}
							}
							for (int i = 0; i < keyToRemove.size(); i ++) {
								String key = (String) keyToRemove.get(i);
								cacheHashMap.remove(key);
							}
							/*
							 * Puts the thread to sleep. Don't need to check it
							 * continuously
							 */
							Thread.sleep(milliSecondSleepTime);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
					return;
				}
			});

			// Sets the thread's priority to the minimum value.
			threadCleanerUpper.setPriority(Thread.MIN_PRIORITY);

			// Starts the thread.
			threadCleanerUpper.start();
		} catch (Exception e) {
			//AppLogger.debug("Cache.Static Block: " + e);
		}
	} /* End static block */

	public Object add(String key, Object value, Date absoluteExpiration, int slidingExpiration) {
		CachedObject obj = (CachedObject) cacheHashMap.get(key);
		if (obj == null)
			obj = new CachedObject(key, value, absoluteExpiration, slidingExpiration);
		obj = (CachedObject) cacheHashMap.put(key, obj);
		return obj == null ? null : obj.getValue();
	}

	public Object get(String key) {
		CachedObject obj = (CachedObject) cacheHashMap.get(key);
		if (obj == null)
			return null;

		if (obj.isExpired()) {
			cacheHashMap.remove(key);
			return null;
		} else {
			obj.updateExpiration();
			return obj.getValue();
		}
	}

	public Object remove(String key) {
		CachedObject obj = (CachedObject) cacheHashMap.remove(key);
		return obj == null ? null : obj.getValue();
	}

	public int getCount() {
		return cacheHashMap.size();
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Cache cache = Cache.getInstance();
		cache.add("key", "hello,world!", null, 1);
		cache.add("key1", "hello,world....", null, 2);
		for (int i = 0; i < 1; i ++) {
			try {
				Thread.sleep(120000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -