标签:
public class KeyGenerator {
private static KeyGenerator keygen=new KeyGenerator();
private static final int POOL_SIZE=20;
private HashMap keyList=new HashMap(10);
private KeyGenerator(){}
public static KeyGenerator geInstance(){
return keygen;
}
/*取值方法,提供下一个合适的键值*/
public synchronized int getNextKey(String keyName)
{
KeyInfo keyInfo=null;
if(keyList.containsKey(keyName)){
keyInfo=(KeyInfo)keyList.get(keyName);
System.out.println("key found");
}
else{
keyInfo=new KeyInfo(POOL_SIZE, keyName);
keyList.put(keyName, keyInfo);
System.out.println("new key created");
}
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/4716877.html