简体   繁体   中英

Guice Singleton and Servlet

I'M using Guice and I have a question. There is a servlet that's Singleton. Is there only one instance of this class in JVM or only one instance of Session scope? And what about concurrency access to this class?

There would be any problem of concurrency access of your servlet resource. Servlet container will handles it well, it will spawn new thread at eaach request and pass that servlet reference and request will be processed.

And it good to make you servlet single threaded which confirm single memory space use, so container will be lightweight. Same concept available in spring where by default every bean is singleton.

I am not sure about Guice , but Container makes sure that only one instance of Servlet exist per JVM per definition in DD , as per the spec unless your Servlet implements the evil SingleThreadModel . The Container will spawn a new thread for each request , invoking the service() method .

Moreover the class and instance variables will not be thread safe . Only the local variables will be thread-safe.

Actually Guice requires servlets that it manages to be Singletons:

Note: Every servlet (or filter) is required to be a @Singleton. If you cannot annotate the class directly, you must bind it using bind(..).in(Singleton.class), separate to the filter() or servlet() rules. Mapping under any other scope is an error. This is to maintain consistency with the Servlet specification. Guice Servlet does not support the deprecated SingleThreadModel.

(from this documentation )

You are responsible for handling concurrent access correctly.

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