java生成16位唯一值做主键

仅限一台服务器

关于多个表主键的生成,在不建议扩展主键长度的前提下,通过对时间戳加锁来解决主键重复问题

import org.apache.commons.lang.StringUtils;

import com.fto.sql.UniqueTimestamp;

public class Test {
	public static UniqueTimestamp UT = new UniqueTimestamp();

	public static String generateId() {
		synchronized (UT) {
			return StringUtils.leftPad(Long.toHexString(UT.getUniqueTimestamp()).toUpperCase(), 16, '0');
		}
	}

	public static void main(String[] args) {
		for (int i = 0; i < 100; i++) {
			new Thread(new Runnable() {
				@Override
				public void run() {
					System.out.println(generateId());
				}
			}).start();
		}
	}
}

 

从100个线程同时执行的结果来看,没有重复,但是目前还有几个疑问:

 

 

1.会不会出现两次执行时间差小于时间戳最小单位?

2.虽然可能解决了问题,但是效率是否降低影响整体?

3.回到问题,除了此方法,是否可以生成16位唯一值?

补充下

package com.fto.sql;

public class UniqueTimestamp
{
  public static final char PRECISION_MILLISECOND = 'S';
  public static final char PRECISION_SECOND = 's';
  public static final char PRECISION_MINUTE = 'm';
  private char precision = 'S';
  private long ts = -1L;
  
  public UniqueTimestamp() {}
  
  public UniqueTimestamp(char prec)
  {
    if ((prec != 'S') && (prec != 's') && (prec != 'm')) {
      throw new IllegalArgumentException("Illegal argument for UniqueTimestamp. Only 'S', 's','m' can be used.");
    }
    this.precision = prec;
  }
  
  public synchronized long getUniqueTimestamp()
  {
    if (this.ts == -1L)
    {
      this.ts = getCurrentTimeValue();
    }
    else
    {
      long t = getCurrentTimeValue();
      if (t <= this.ts) {
        this.ts += 1L;
      } else {
        this.ts = t;
      }
    }
    return getReturnValue(this.ts);
  }
  
  private long getCurrentTimeValue()
  {
    long ts;
    switch (this.precision)
    {
    case 'S': 
    default: 
      ts = System.currentTimeMillis();
      break;
    case 's': 
      ts = System.currentTimeMillis() / 1000L;
      break;
    case 'm': 
      ts = System.currentTimeMillis() / 60000L;
    }
    return ts;
  }
  
  private long getReturnValue(long ts)
  {
    switch (this.precision)
    {
    case 'S': 
    default: 
      return ts;
    case 's': 
      return ts * 1000L;
    }
    return ts * 60000L;
  }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值