Implementation of single-instance mode of Sequence key generator

Source: Internet
Author: User

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;
}
/* Value method, provide the next appropriate key value */
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++;
}
/*
* Extract current key values from the database
* */
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;
}
}

Implementation of single-instance mode of Sequence key generator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.