simpleidgenerator.java

来自「100多M的J2EE培训内容」· Java 代码 · 共 41 行

JAVA
41
字号
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;  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?