笔记:将FileItem存放于缓存

阅读更多
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.fileupload.FileItem;

/**
 * 
 * @ClassName: FileItemHelper
 * @description: 存放临时文件,此类仅支持文件较小,并且存放时间极短的文件,除此类型的文件请存放于硬盘。
 * @author: QUINN
 * @date: 2014年6月4日 上午10:47:53
 * @version: V1.0
 * 
 */
public class FileItemHelper {

	private FileItemHelper() {

	}

	// 临时文件存放时间 超时4分钟
	private final int TIMEOUT = 1000 * 60 * 4;

	private boolean isCheck = false;

	private static FileItemHelper INSTANCE;

	public static FileItemHelper getInstance() {
		if (FileItemHelper.INSTANCE == null) {
			synchronized (sync) {
				if (FileItemHelper.INSTANCE == null)
					FileItemHelper.INSTANCE = new FileItemHelper();
			}
		}
		return FileItemHelper.INSTANCE;
	}

	// 线程锁对象
	private static Object sync = 1;

	public String putItem(FileItem item) {
		synchronized (sync) {
			String uuid = UUID.randomUUID().toString().replace("-", "");
			datas.put(uuid, item);
			timeouts.put(uuid, System.currentTimeMillis());
			isCheck = true;
			this.checkThread.start();
			return uuid;
		}
	}

	private Thread checkThread = new Thread() {
		public void run() {
			while (true) {
				if (isCheck)
					synchronized (sync) {
						if (timeouts.isEmpty()) {
							isCheck = false;
							break;
						}
						long now = System.currentTimeMillis();
						Iterator ite = timeouts.keySet().iterator();
						while (ite.hasNext()) {
							String key = ite.next();
							long time = timeouts.get(key);
							if (now - time > TIMEOUT) {
								datas.remove(key);
								ite.remove();
							}
						}
					}

				try {
					Thread.sleep(5 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
	};

	/**
	 * 
	 * 
	 * @Title: getFileItem
	 * @Description: 获取了FileItem后会自动删除
	 * @param: 

* @param key * @param:

* @return

* @date: 2014年6月4日 * @return: FileItem * @throws * */ public FileItem getFileItem(String key) { synchronized (sync) { FileItem item = this.datas.get(key); this.datas.remove(key); this.timeouts.remove(key); if (timeouts.isEmpty()) this.isCheck = false; return item; } } // 存文件 private Map datas = new HashMap(); // 超时时间 private Map timeouts = new HashMap(); }

你可能感兴趣的:(笔记:将FileItem存放于缓存)