proper usage of synchronized singleton?

前端 未结 10 722
长发绾君心
长发绾君心 2020-12-31 12:09

So I am thinking about building a hobby project, one off kind of thing, just to brush up on my programming/design.

It\'s basically a multi threaded web spider, upda

10条回答
  •  时光取名叫无心
    2020-12-31 12:16

    Double-checked locking has been proven to be incorrect and flawed (as least in Java). Do a search or look at Wikipedia's entry for the exact reason.

    First and foremost is program correctness. If your code is not thread-safe (in a multi-threaded environment) then it's broken. Correctness comes first before performance optimization.

    To be correct you'll have to synchronize the whole getInstance method

    public static synchronized Singleton getInstance() {
       if (instance==null) ...
    }
    

    or statically initialize it

    private static final Singleton INSTANCE = new Singleton();
    

提交回复
热议问题