原子整数IncrementAndGet()线程安全吗? [英] Is Atomic Integer incrementAndGet() thread safe?

查看:473
本文介绍了原子整数IncrementAndGet()线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Atomic IntegercrementAndAnd()方法线程安全吗?我没有在其中看到任何使用synced关键字的信息.我正在使用以下代码来生成唯一ID:

Is Atomic Integer incrementAndGet() method thread safe? I don't see any use of synchronized keyword in it. I am using following code to generate the unique id:

public enum UniqueIdGenerator {
    INSTANCE;

    private AtomicLong instance = new AtomicLong(System.currentTimeMillis());

    public long incrementAndGet() {
        return instance.incrementAndGet();
    }
}

如果要调用该方法以生成唯一ID的多个线程会导致任何问题,我在徘徊吗?

I am wandering if multiple threads that would call the method to generate unique ID would result in any issue?

UniqueIdGenerator.INSTANCE.incrementAndGet()

谢谢!

推荐答案

是的.它使用基于内部JDK类Unsafe

Yes, it is. It uses other, than synchronized, more efficient thread safety mechanism based on internal JDK class named Unsafe

这篇关于原子整数IncrementAndGet()线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆