I want to have thread save method that returns a unique current Timestamp.Even when the method is called by same time i want to get a unique current datetime.Even if this method is called by making multiple instances of MyClass i want it be be thread 开发者_C百科safe always
class Myclass{
Date getUniquetimeStam(){
synchronized(Myclass.class){
//return date here
}
}
Now if i make 2 instances of Myclass and call getUniqueStam at same ,is it gaurented to return uniue date time.
You can't guarantee unique time for each call. But you can for instance increment it manually if it didn't change yet:
private AtomicLong lastTime = new AtomicLong();
long getUniquetimeStam() {
while (true) { // way of working with atomics, but they are really fast
long now = System.currentTimeMillis();
long last = lastTime.get();
if (last < now) {
if (lastTime.compareAndSet(last, now))
return now;
} else
return lastTime.incrementAndGet();
}
}
No, you are not guaranteed. If your computer is fast enough then both method calls can happen in same millisecond and produce identical Date object.
You have 2 options here:
- Use UUID instead of date. Read more about it here . UUID by specification is guaranteed to be unique each time you generate it - so it's the safest and easiest option you can get.
- Store the date object, synchronize on it, and check if it's the same. Here's an example:
.
class Myclass {
//Static to make it possible to synchronize between instances of Myclass
static Date lastDate;
Date getUniqueTimeStamp() {
synchronized (Myclass.lastDate) {
Date newDate = new Date();
if (newDate.getTime() <= Myclass.lastDate.getTime()) {
newDate.setTime(Myclass.lastDate.getTime()+1);
}
Myclass.lastDate.setTime(newDate.getTime());
return newDate;
}
}
}
Not cool though - you can add a delay and then create the Data.
class Myclass {
Date getUniquetimeStam() {
//in try catch
Thread.sleep(100);
//
new Date();
}
}
Could you just change it to return a new instance of Date on every call?
class Myclass {
Date getUniquetimeStam() {
new Date();
}
}
精彩评论