替代java中的synchronized块

Sam*_*Sam 10 java multithreading synchronization thread-safety thread-synchronization

我只使用以下代码startTime设置一次保证变量:

public class Processor
{
    private Date startTime;

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

        // do somethings
    }
}
Run Code Online (Sandbox Code Playgroud)

我将通过此代码保证变量实例化一次仅用于任何数量的调用process方法调用.

我的问题是:

是否有替代方法可以使我的代码更简洁?(用于样本删除ifsynchronized陈述)

yeg*_*256 11

使用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
  }
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 10

根据您的评论,您可以使用AtomicReference

firstStartTime.compareAndSet(null, new Date());
Run Code Online (Sandbox Code Playgroud)

或AtomicLong

firstStartTime.compareAndSet(0L, System.currentTimeMillis());
Run Code Online (Sandbox Code Playgroud)

我会用

private final Date startTime = new Date();
Run Code Online (Sandbox Code Playgroud)

要么

private final long startTime = System.currentTimeMillis();
Run Code Online (Sandbox Code Playgroud)