筆記:將FileItem存放於快取

年華是封無效信發表於2014-06-04

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<String> 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: <p>
* @param key
* @param: <p>
* @return <p>
* @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<String, FileItem> datas = new HashMap<String, FileItem>();
// 超時時間
private Map<String, Long> timeouts = new HashMap<String, Long>();


}

相關文章