java 当天唯一ids,Java:唯一的10位ID

I need to generate a unique 10 digit ID in Java. These are the restrictions for this ID:

Only Numeric

Maximum 10 digits

Possible to create up to 10 different IDs per second

Has to be unique (even if the application re-starts)

Not possible to save a number in the Database

As fast as possible NOT to add much lattency to the system

The best solution I found so far is the following:

private static int inc = 0;

private static long getId(){

long id = Long.parseLong(String.valueOf(System.currentTimeMillis())

.substring(1,10)

.concat(String.valueOf(inc)));

inc = (inc+1)%10;

return id;

}

This solution has the following problems:

If for any reason there is a need to create more than 10 IDs per seccond, this solution won't work.

In about 32 years this ID could be repeated (This is probably acceptable)

Any other solution to create this ID?

Any other problem I haven't thought of with mine?

Thanks for your help,

解决方案

This is a small enhancement to yours but should be resilient.

private static final long LIMIT = 10000000000L;

private static long last = 0;

public static long getID() {

// 10 digits.

long id = System.currentTimeMillis() % LIMIT;

if ( id <= last ) {

id = (last + 1) % LIMIT;

}

return last = id;

}

As it is it should manage up to 1000 per second with a comparatively short cycle rate. To extend the cycle rate (but shorten the resolution) you could use (System.currentTimeMillis() / 10) % 10000000000L or (System.currentTimeMillis() / 100) % 10000000000L.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值