Alternative for synchronized block in java

Sam picture Sam · Jul 25, 2012 · Viewed 8.7k times · Source

I use following code for guarantee startTime variable set once only:

public class Processor
{
    private Date startTime;

    public void doProcess()
    {
        if(startTime == null)
            synchronized(this)
            {
                  if(startTime == null)
                  {
                     startTime = new Date();
                  }
            }

        // do somethings
    }
}

I will guarantee by this code for variable instantiated once only for any number of invoking process method call.

My question is:

Is there alternative approach for my code be more concise? (for sample remove if & synchronized statements)

Answer

yegor256 picture yegor256 · Jul 25, 2012

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
  }
}