关于java:在构造函数中自动初始化int messageID

Automatically initializing an int messageID in a constructor

如何在Java的构造函数中将最终int初始化为比以前的实例大1,我可以这样做吗?我的意思是我有一个final int messageID;,它对于每个实例都必须是唯一的,我该怎么做?


保持

1
private static final AtomicInteger NEXT_MESSAGE_ID = new AtomicInteger();

然后在构造函数中执行

1
this.messageId = NEXT_MESSAGE_ID.getAndIncrement();


一种解决方案是使用静态变量来保存最大的消息ID,然后在每次创建新对象时将其递增。

1
2
3
4
5
6
7
8
class Foo {
    static int maxMessageID = 0;
    final int messageID;

    public Foo() {
        this.messageID = ++maxMessageID;
    }
}

编辑

为使此线程安全,请使用synchronized将变量的增量放入方法中。

1
2
3
4
5
6
7
8
9
10
11
12
class Foo {
    static int maxMessageID = 0;
    final int messageID;

    public Foo() {
        this.messageID = this.getID();
    }

   private synchronized int getID() {
       return ++maxMessageID;
   }
}