Aya*_*yan 9 java multithreading sequence
我打算编写一个序列生成器,它将在post期间用于我的REST资源实现类,以生成唯一的id.由于每个post请求都由单独的线程处理,我使变量volatile和方法同步.我没有选择使用序列或传统RDBMS提供的东西.
public class SequenceGen {
    volatile static int n = 0;  
    public synchronized int nextNum(){
        return n++;
    }   
}
这是我到目前为止,并计划在我的REST实现中创建SequenceGen的变量.我的实际问题是它会在某个地方破裂吗?我测试了两个线程,我没有看到重复的任何值.
ant*_*tix 23
它可以工作,但是AtomicInteger内置类型,非常适合您的用例.
AtomicInteger seq = new AtomicInteger();
int nextVal = seq.incrementAndGet();
| 归档时间: | 
 | 
| 查看次数: | 28864 次 | 
| 最近记录: |