Alternative for synchronized block in java Alternative for synchronized block in java multithreading multithreading

Alternative for synchronized block in java


Based on you comments, you could use AtomicReference

firstStartTime.compareAndSet(null, new Date());

or AtomicLong

firstStartTime.compareAndSet(0L, System.currentTimeMillis());

I would use

private final Date startTime = new Date();

or

private final long startTime = System.currentTimeMillis();


Use AtomicReference:

public class Processor {  private final AtomicReference<Date> startTime = new AtomicReference<Date>();  public void doProcess() {    if (this.startTime.compareAndSet(null, new Date())) {      // do something first time only    }    // do somethings  }}


Your code is an example of so called "double check locking." Please read this article. It explains why this trick does not work in java although it is very smart.