java - making a method thread safe even when method is called by makeing multiple instances of class -
i want have thread save method returns unique current timestamp.even when method called same time want unique current datetime.even if method called making multiple instances of myclass want be thread safe always
class myclass{ date getuniquetimestam(){ synchronized(myclass.class){ //return date here } }
now if make 2 instances of myclass , call getuniquestam @ same ,is gaurented return uniue date time.
no, not guaranteed. if computer fast enough both method calls can happen in same millisecond , produce identical date object.
you have 2 options here:
- use uuid instead of date. read more here . uuid specification guaranteed unique each time generate - it's safest , easiest option can get.
- store date object, synchronize on it, , check if it's same. here's example:
.
class myclass { //static make possible 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; } } }
Comments
Post a Comment