tags:

views:

93

answers:

2

Hi, 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.

+2  A: 

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.

jldupont
+4  A: 
  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.
Michael Borgwardt
My app is distributed. Frankly, message should generate id by itself.How about timestamp?
Sorantis
with a timestamp: you'll find it more difficult to deal with clock synchronization issues IMO...
jldupont
"How about timestamp?" Can messages originate on more than one machine? Then you have a possible collision. Even if not, you'd need to ensure that two messages can not be created within the granularity of the timestamp (e.g. two messages created during the same millisec if timestamp is down to the millisecond).
Kris
@Sorantis: nope, timestamps can collide far too easily.
Michael Borgwardt