Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for synchronized block in java

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)

like image 906
Sam Avatar asked Jul 25 '12 12:07

Sam


Video Answer


3 Answers

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();
like image 64
Peter Lawrey Avatar answered Oct 20 '22 00:10

Peter Lawrey


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
  }
}
like image 40
yegor256 Avatar answered Oct 19 '22 23:10

yegor256


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.

like image 41
AlexR Avatar answered Oct 20 '22 00:10

AlexR