简体   繁体   中英

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.

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.

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

So you are absolutely right :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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