Object Lock for unique values

Hi I have one synchronized method which returns ms. Can anyone tell whether where each object will get the unique value in below code.

public static synchronized Long generateIdforDCR() 
         {  
        int val= return System.nanoTime();
        } 

Call will be in another class like

forloop 1... 1000
{
   ClassName cn=new ClassName();
   cn.generateIdforDCR();

}

Will i get unique value always.

Jon Skeet
people
quotationmark

No - there's no guarantee that each call will return a different value. It's not inconceivable that the call (including synchronization) could take less time than the granularity of the internal clock used for nanoTime(). (Indeed, I can see this happen on my laptop.)

It sounds like you should just be using an AtomicLong instead:

private static final AtomicLong counter = new AtomicLong();

public static Long generateIdforDCR() {
    return counter.incrementAndGet();
}

That will give you a unique number (if you call it fewer than 264 times) within that run. If you need it to be unique within a larger scope (e.g. across multiple sequential runs, or potentially multiple concurrent runs of different processes) then you'll need a slightly different approach.

people

See more on this question at Stackoverflow