简体   繁体   English

静态最终字段的同步吸气剂

[英]Synchronized getter of a static final field

I'm looking at the code fragment below and I frankly do not understand what the idea behind making this particular getter synchronized.我正在查看下面的代码片段,坦率地说,我不明白使这个特定的 getter 同步背后的想法是什么。

public class MVELSafeHelper {
  private static final MVELEvaluator evaluator;
  static {
    evaluator = KiePolicyHelper.isPolicyEnabled() ? new SafeMVELEvaluator() : new RawMVELEvaluator();
  }
  public static synchronized MVELEvaluator getEvaluator() {
    return evaluator;
  }
//
}

I'm not an expert in concurrency and I believe the people at the Drools project are far more experienced than me but I'm just wondering whether this is a typo or this construct might be worthwhile in some cases and therefore 40% of my server's CPU time isn't being spent for nothing.我不是并发方面的专家,我相信 Drools 项目的人比我更有经验,但我只是想知道这是否是一个错字或这种构造在某些情况下是否值得,因此我服务器的 40% CPU 时间不会白白浪费。

In this instance the synchronized keyword is not required, as the MVELEvaluator is instantiated once in a static block, and whose reference cannot be changed because it is declared final.在这种情况下,synchronized 关键字不是必需的,因为 MVELEvaluator 在静态块中实例化一次,并且其引用不能更改,因为它被声明为 final。 So there's no need to control access to its reference for multiple threads.所以没有必要控制对多个线程的引用的访问。

Concurrency issue already been taken care by declaring variable as final, static and there are no setter.并发问题已经通过将变量声明为 final、static 并且没有 setter 来处理。 So I don't see necessity of keeping method synchronized.所以我认为没有必要保持方法同步。

If it was about variable instantiation then since its in static block it will be executed before getter call anyway.如果它是关于变量实例化,那么由于它在静态块中,它将在 getter 调用之前执行。

So you are absolutely right :)所以你是绝对正确的:)

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

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