java - Using new Date() as unique identifier -
imagine have proccess creates 1000 entities each second. each of these entities call setter :
newentity.setdate(new date());
1) possible 2 entities recieve same date? or safe assume unique identifier effect date field?
2) if answer question #1 :"yes" - let's make minor tweak: lets create function:
public static synchronized date getdate() { return new date(); }
will work now?
newentity.setdate(getdate());
3)
system.nanotime()?
edit 4) :
public static synchronized date getdate() { thread.sleep(1000); return new date(); }
thanks.
a simple test shows 2 consecutive calls new date()
can return same date. making method synchronized won't make difference.
if need unique id, use atomicinteger counter
, return counter.getandincrement();
new ids.
ps: using system.nanotime()
won't either resolution os , processor dependent , low enough 2 consecutive calls can return same result too.
edit
your 4th proposal sleep second in synchronized method solve unicity issue (although pointed out yshavit, nothing in javadoc guarantees it). note using date unique id bad idea in itself: dates mutable calling code change id settime
method (by mistake or on purpose).
finally, if want id date related, use long representing milliseconds since epoch , keep track of existing ids - this:
private static final set<long> usedids = new hashset<> (); public static synchronized long getuniqueid() { long millis; { millis = system.currenttimemillis(); } while (!usedids.add(millis)); return millis; }
Comments
Post a Comment