Sorantis
Sorantis

Reputation: 14702

Creating message id in java

I need to uniquely identify messages in my app. Thus each message should contain its id. I have a couple of questions though..

  1. Should message generate its id privately and only provide getter for id?
  2. What is the best way to create ids? Any alternatives to UUID class in java?

Thanks.

Upvotes: 3

Views: 2355

Answers (2)

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

  1. Obviously, the ID should not have a public setter. An alternative to having the message generate the ID itself is to pass it in the constructor.
  2. If your app is distributed, there is no real alternative to a UUID. If it's not distributed, AtomicInteger or AtomicLong are good alternatives that can be used concurrectly without locking.

Upvotes: 6

jldupont
jldupont

Reputation: 96716

Without more context I would answer: if you are concerned about speed, you could always have a process (on an other machine?) pre-compute the UUIDs for the application. This way, the application could have quick access to a "pool" of UUIDs.

  1. One shouldn't be able to the change the UID of a message or else what is the point?

  2. What's wrong with UUID class ? if it is about speed, then see above.

Upvotes: 2

Related Questions