ProgramFan.com
回到首页 设为首页 加入收藏 网站留言
人才招聘频道
编程爱好者BLOG
编程爱好者论坛
首页 | 论坛 | BLOG | 人才招聘 | 书评 | 文章 | 资讯 | 下载 | 源码 | 项目交易 | 兴趣小组 | 网友作品 | 资源共享 | 收藏夹 | ACM题库 | VBAPI查询 | 刻盘服务
 您所在的位置:编程爱好者网站文档中心JAVA文章 - 正文
 

JAVA ID生成器生成逻辑主键

(加入日期:2007-11-6 点击数:1308)
收藏文章】【对此文发表评论】【保存文章至硬盘】【打印文章】【字体:


在一个数据库设计里,假如使用了逻辑主键,那么你一般都需要一个ID生成器去生成逻辑主键。 

在许多数据库里面,都提供了ID生成的机制,如Oracle中的sequence,MSSQL中的identity,可惜这些方法各种数据库都不同的,所以很多人愿意找寻一种通用的方式。 

编写代码,1、2、3……这样一直累加是最直接的想法,JAVA用以下方式去实现 


private static AtomicInteger uniqueId = new AtomicInteger(0);

public static String nextId() {
return Integer.toString(uniqueId.incrementAndGet());
}

 


当然,这样太简单了,并且一重新启动,计数器就归 0 了,一般的做法可以用 时间 + 计数器 的方式, 


private static final long ONE_STEP = 10;
private static final long BASE = 1129703383453l;

private static final Lock LOCK = new ReentrantLock();

private static long lastTime = System.currentTimeMillis();
private static short lastCount = 0;

/**
* a time (as returned by {@link System#currentTimeMillis()}) at which
* the VM that this UID was generated in was alive
* @serial
*/
private final long time;

/**
* 16-bit number to distinguish UID instances created
* in the same VM with the same time value
* @serial
*/
private final short count;

/**
* Generates a UID that is unique over time with
* respect to the host that it was generated on.
*/
public UID() {
LOCK.lock();
try {
if (lastCount == ONE_STEP) {
boolean done = false;
while (!done) {
long now = System.currentTimeMillis();
if (now == lastTime) {
// pause for a second to wait for time to change
try {
Thread.currentThread().sleep(1);
}
catch (java.lang.InterruptedException e) {
} // ignore exception
continue;
}
else {
lastTime = now;
lastCount = 0;
done = true;
}
}
}
time = lastTime;
count = lastCount++;
}
finally {
LOCK.unlock();
}
}

在一个群集的环境里面,通常还需要加上IP的前缀,即 IP + 时间 + 计数器,这个就是JAVA原版本的实现了。 
 
本栏文章均来自于互联网,版权归原作者和各发布网站所有,本站收集这些文章仅供学习参考之用。任何人都不能将这些文章用于商业或者其他目的。( ProgramFan.Com )

对此文发表评论】 【编程爱好者论坛】 【关闭窗口

 
 
 
 
 
 

最新招聘信息

 
 


关于本站 - 网站导航 - 广告服务 - 诚邀加盟 - 联系站长友情链接赞助本站
Copyright© 1999-2008 Programfan.com. All Rights Reserved
网站制作&维护:Hannibal    Email: webmaster@pfan.cn