![](/img/trans.png)
[英]Is there an alternative way to write a synchronized block in Java using CAS operations?
[英]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
方法調用。
我的問題是:
是否有替代方法可以使我的代碼更簡潔? (對於樣本刪除if
和synchronized
語句)
使用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();
// ...
}
簡潔到你?
所以根據我的理解,你需要一個單身人士:
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 if
和synchronized
關鍵字的例子,我告訴你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.