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?
Asked
Active
Viewed 93 times
0
-
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 Answers
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
-
-
1
-
1My university professor does not allow us to use things we have not learnt yet.. It's a bit silly, I know... – I.Anchev Jun 18 '14 at 11:13
-
Then you have to go with the other proposed answer, although it is not threadsafe. – Ray Jun 18 '14 at 11:15
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
-
@assylias That is true. I just wanted to show how it can be done using simple techniques. – Jørgen R Jun 18 '14 at 11:17