SimpleIdGenerator.java
资源名称:某公司的java培训教材 [点击查看]
上传用户:dinglihq
上传日期:2013-02-04
资源大小:99958k
文件大小:1k
源码类别:
Java编程
开发平台:
Java
- package com.borland.training.meetings.entities;
- import java.security.SecureRandom;
- // This class implements a simple primary key generator.
- // A generated primary key is a concatenation of the current time in milliseconds
- // and a random number.
- public class SimpleIdGenerator implements IdGenerator {
- private static SimpleIdGenerator instance = null;
- private SecureRandom secureRandom;
- private SimpleIdGenerator() {
- try {
- secureRandom = SecureRandom.getInstance("SHA1PRNG");
- }
- catch (java.security.NoSuchAlgorithmException e) {
- System.err.println("PRNG algorithm not available");
- }
- }
- public static SimpleIdGenerator getInstance() {
- if(instance == null) {
- instance = new SimpleIdGenerator();
- }
- return instance;
- }
- public long generateId() {
- int random = secureRandom.nextInt();
- long timeNow = System.currentTimeMillis();
- int timeLow = (int) timeNow & 0xFFFFFFFF;
- if(timeLow < 0) timeLow = timeLow * -1;
- long highId = random;
- highId = highId << 32;
- long lowId = timeLow;
- long id = lowId | highId;
- return id;
- }
- }