proper usage of synchronized singleton?

前端 未结 10 726
长发绾君心
长发绾君心 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:29

    Using lazy initialization for the database in a web crawler is probably not worthwhile. Lazy initialization adds complexity and an ongoing speed hit. One case where it is justified is when there is a good chance the data will never be needed. Also, in an interactive application, it can be used to reduce startup time and give the illusion of speed.

    For a non-interactive application like a web-crawler, which will surely need its database to exist right away, lazy initialization is a poor fit.

    On the other hand, a web-crawler is easily parallelizable, and will benefit greatly from being multi-threaded. Using it as an exercise to master the java.util.concurrent library would be extremely worthwhile. Specifically, look at ConcurrentHashMap and ConcurrentSkipListMap, which will allow multiple threads to read and update a shared map.

    When you get rid of lazy initialization, the simplest Singleton pattern is something like this:

    class Singleton {
    
      static final Singleton INSTANCE = new Singleton();
    
      private Singleton() { }
    
      ...
    
    }
    

    The keyword final is the key here. Even if you provide a static "getter" for the singleton rather than allowing direct field access, making the singleton final helps to ensure correctness and allows more aggressive optimization by the JIT compiler.

提交回复
热议问题