开发者

making a method thread safe even when method is called by makeing multiple instances of class

开发者 https://www.devze.com 2023-03-22 02:15 出处:网络
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 mu

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:

  1. 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.
  2. 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();
  }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号