Java中的序列生成器,用于唯一ID [英] Sequence Generator in Java for Unique Id
问题描述
我打算在post期间编写一个序列生成器,在我的REST资源实现类中使用
生成
唯一id。由于每个post请求都由单独的线程处理,
我使变量volatile和方法同步。
我没有选择使用序列或传统RDBMS提供的
。
I am planning to write a sequence generator which will be used in my REST resource implementation class during post to generate unique id. Since every post request is handled by separate thread, I made the variable volatile and method synchronized. I don't have option to use sequences or something which traditional RDBMS provides.
public class SequenceGen {
volatile static int n = 0;
public synchronized int nextNum(){
return n++;
}
}
这是我到目前为止所做的,并计划到在我的REST实现中创建
SequenceGen的变量。我的实际问题是它会在某个地方突破吗?我测试了两个线程,我没有看到
任何值重复。
this is what I have so far, and planning to create a variable of SequenceGen in my REST Implementation. My actual question is will it break somewhere ? I tested with two threads and I dont see any value repeated.
推荐答案
它会工作,但是 AtomicInteger
是一种内置类型,非常适合您的使用案例。
It will work, however AtomicInteger
is an built in type that is perfect for your use case.
AtomicInteger seq = new AtomicInteger();
int nextVal = seq.incrementAndGet();
这篇关于Java中的序列生成器,用于唯一ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!