繁体   English   中英

替代java中的synchronized块

[英]Alternative for synchronized block in java

我使用以下代码来保证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语句)

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

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

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

或AtomicLong

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

我会用

private final Date startTime = new Date();

要么

private final long startTime = System.currentTimeMillis();

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

总结其他海报已经解释过:

private volatile Date startTime;

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

简洁到你?

所以根据我的理解,你需要一个单身人士:

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

1您使用的是double checked locking

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

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

3. if你想要一个带有No ifsynchronized关键字的例子,我告诉你Initialize the static variable during declaration. 办法。

public class MyClass{

  private static MyClass unique = new MyClass();

  private MyClass{}

  public static MyClass getInstance(){

      return unique;

  }

 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM