0

How can I initialize a final int in the constructor in Java to be with 1 bigger than the previous instance and can I do that at all? I mean i have a final int messageID; which must be unique for every instance, how can I do that?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
I.Anchev
  • 83
  • 1
  • 5
  • possible duplicate of [Final variable manipulation in Java](http://stackoverflow.com/questions/1249917/final-variable-manipulation-in-java) – Alexandru Cimpanu Jun 18 '14 at 11:06
  • you need something like this http://stackoverflow.com/a/3478862/821057 – Zaheer Ahmed Jun 18 '14 at 11:06
  • possible duplicate of [how many instances for a class exists at runtime in java](http://stackoverflow.com/questions/3478795/how-many-instances-for-a-class-exists-at-runtime-in-java) – Zaheer Ahmed Jun 18 '14 at 11:06
  • Possible duplicate of http://stackoverflow.com/questions/12336030/automatic-id-generation – Raedwald Jun 18 '14 at 11:44

2 Answers2

5

Keep a

private static final AtomicInteger NEXT_MESSAGE_ID = new AtomicInteger();

Then in your constructor do

this.messageId = NEXT_MESSAGE_ID.getAndIncrement();
Ray
  • 3,084
  • 2
  • 19
  • 27
0

A soulution could be to use a static variable to hold the largest message ID, then increment it each time a new object is created.

class Foo {
    static int maxMessageID = 0;
    final int messageID;

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

EDIT

To make this thread safe, put the incrementing of the variable inside a method using synchronized.

class Foo {
    static int maxMessageID = 0;
    final int messageID;

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

   private synchronized int getID() {
       return ++maxMessageID;
   }
}
Jørgen R
  • 10,568
  • 7
  • 42
  • 59