java缓存

这个是自己写的用来缓存信息的类。
public class UserAbilityCache {

	private Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());;

	private static UserAbilityCache cache = new UserAbilityCache();

	private UserAbilityCache() {
		Thread t = new timerThread();
		t.setDaemon(true);
		t.start();
	}
	
	public static UserAbilityCache getInstance() {
		return cache;
	}

	private void clear() {
		map.clear();
	}

	public boolean containsKey(String key) {
		if (map.containsKey(key)) {
			return true;
		}
		return false;
	}

	public void put(String key, String value) {
		map.put(key, value);
	}

	public String get(String key) {
		return map.get(key);
	}
	
         //定时器,没隔一段时间清空map里的数据。
	private class timerThread extends Thread {
		public static final int PERIOD = 2 * 60 * 1000; // two minutes
		public boolean done = false;
		public void run() {
			while (!done) {
				try {
					clear();
					Thread.sleep(PERIOD);
				} catch (InterruptedException ex) {
				}
			}
		}
	}
}

类的使用情况是这样的。
public String getAbility(){
   UserAbilityCache cache = UserAbilityCache.getInstance();//获取个实例
		String account = requestData.getAccount();
		if(cache.containsKey(account)){
			ability = cache.get(account);
		}else{
		  //查询数据库
                        ....					ResultSet rs = stat.executeQuery();
				while (rs.next()) {
					ability = rs.getString(1);
					cache.put(account, ability);
				}
			} catch (SQLException e) {
			}
		}
    return ability ;
}

各位路过的高手们,各抒己见,看我这样写有没有什么问题?

你可能感兴趣的:(java,thread,cache)