简体   繁体   English

在不同的servlet之间共享资源

[英]sharing a resource among different servlets

Let's say I have a certain resource S (for instance a strange database that uses the filesystem) and I have a certain Java class R that manage that resource (it prvides high level api and manages stuff like concurrency necessary in the use of S). 假设我有一个特定的资源S(例如,一个使用文件系统的奇怪数据库),并且我有一个特定的Java类R来管理该资源(它包含高级api并管理诸如使用S所必需的并发之类的东西)。 Now I have the constraint that if an instance of R manages S then no other instance of R can access to S at the same time. 现在,我有了一个约束,即如果R的一个实例管理S,则R的其他任何实例都不能同时访问S。

Now, let's assume I have a servlet V1 that needs to access S through R. I want to allow many users to work with V1 concurrently, so since the container will assign a new thread of V1 to each user, I thought to make R static, initilize it in the init() method so as to share it among the threads. 现在,假设我有一个Servlet V1,它需要通过R访问S。我想允许许多用户同时使用V1,因此,由于容器将为每个用户分配一个新的V1线程,因此我想将R静态化,请在init()方法中对其进行初始化,以便在线程之间共享它。 Is this ok? 这个可以吗?

case two: Now I have M different servlets V1,...,VM each accessible from many users. 案例二:现在,我有M个不同的servlet V1,...,VM,每个用户都可以访问。 Now I want that all these servlets can have a rw access to S. I must access S through R and I can't simply use an instance of R for each servlet because only one instance at time can deal with S. Is there any way to share R among all the threads of all the servlets? 现在,我希望所有这些servlet都可以对S进行rw访问。我必须通过R访问S,并且我不能简单地为每个servlet使用R的实例,因为当时只有一个实例可以处理S。在所有servlet的所有线程之间共享R?

ps. PS。 R in my case is an embedded database like neo4j. 就我而言,R是像neo4j这样的嵌入式数据库。

You can have a static initializer on R to create the one and only instance of R and store it in some static field (accessible via a static getter). 您可以在R上使用静态初始化程序来创建R的唯一实例并将其存储在某个静态字段中(可通过静态getter访问)。

You could also create and initialize one instance of R by implementing a ServletContextListener . 您还可以通过实现ServletContextListener创建和初始化R的一个实例。 The contextInitialized method is called when the web app starts. Web应用程序启动时将调用contextInitialized方法。

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

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