标签:
public class MutilKeyGenerator {
private static HashMap keys=new HashMap();
private static final int POOL_SIZE=20;
private KeyInfo keyInfo=null;
private MutilKeyGenerator(){}
private MutilKeyGenerator(String keyName){
keyInfo=new KeyInfo(POOL_SIZE, keyName);
}
/*
* 静态工厂提供自己的实例
* */
public synchronized static MutilKeyGenerator getInstance(String keyName){
MutilKeyGenerator keyGenerator=null;
if(keys.containsKey(keyName)){
keyGenerator=(MutilKeyGenerator)keys.get(keyName);
System.out.println(keyName+" founded");
}
else{
keyGenerator=new MutilKeyGenerator(keyName);
keys.put(keyName, keyGenerator);
System.out.println(keyName+" created");
}
return keyGenerator;
}
public int getNextKey(){
return keyInfo.getNextKey();
}
}
class KeyInfo
{
private int keyMax;
private int keyMin;
private int nextKey;
private int poolSize;
private String keyName;
public KeyInfo(int poolSize,String keyName)
{
this.poolSize=poolSize;
this.keyName=keyName;
retriveFromDB();
}
public int getKeyMax(){
return keyMax;
}
public int getKeyMin(){
return keyMin;
}
public int getNextKey()
{
if(nextKey>keyMax){
retriveFromDB();
}
return nextKey++;
}
/*
* 从数据库提取当前的键值
* */
private void retriveFromDB()
{
String sql1="update keyTable set keyValue=keyValue+"+poolSize+"where keyname=‘"+keyName+"‘";
String sql2="select keyValue from keyTable where keyName=‘"+keyName+"‘";
//excute the sql,assume the value returned is 1000
int keyFromDB=1000;
this.keyMax=keyFromDB;
this.keyMin=keyFromDB-poolSize+1;
this.nextKey=keyMin;
}
}
标签:
原文地址:http://www.cnblogs.com/xtsylc/p/4716878.html