10

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

public class Processor
{
    private Date startTime;

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

        // do somethings
    }
}

我将通过此代码保证只为任意数量的调用process方法调用实例化一次变量。

我的问题是:

我的代码是否有更简洁的替代方法?(用于示例删除ifsynchronized语句)

4

6 回答 6

11

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

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

或 AtomicLong

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

我会用

private final Date startTime = new Date();

或者

private final long startTime = System.currentTimeMillis();
于 2012-07-25T12:18:10.753 回答
11

使用原子参考

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
  }
}
于 2012-07-25T12:19:34.997 回答
4

您的代码是所谓的“双重检查锁定”的示例。请阅读这篇文章。它解释了为什么这个技巧在 java 中不起作用,尽管它非常聪明。

于 2012-07-25T12:19:35.480 回答
2

总结一下其他海报已经解释过的内容:

private volatile Date startTime;

public void doProcess()
{
   if(startTime == null) startTime = new Date();
   // ...
}

对你来说够简洁了吗?

于 2012-07-25T12:36:31.243 回答
2

因此,据我了解,您需要一个单例,即:

  1. 简短,易于实施/理解。
  2. doProcess仅在被调用时初始化。

我建议使用嵌套类进行以下实现:

public class Processor {
    private Date startTime;

    private static class Nested {
        public static final Date date = new Date();
    }

    public void doProcess() {
        startTime = Nested.date; // initialized on first reference
        // do somethings
    }
}
于 2012-07-25T12:43:17.437 回答
0

1您使用的称为double checked locking.

2.还有另外 2 种方法可以做到这一点

  - Use synchronized on the Method
  - Initialize the static variable during declaration.

3.由于您想要一个带有 Noifsynchronized关键字的示例,我正在向您展示Initialize the static variable during declaration.方式。

public class MyClass{

  private static MyClass unique = new MyClass();

  private MyClass{}

  public static MyClass getInstance(){

      return unique;

  }

 }
于 2012-07-25T12:21:45.730 回答