抽象问题
将资源加载到将在 Java 应用程序服务器中的 servlet 之间共享的内存中的最佳方法是什么?
我实际上在做什么
我想创建一个监视队列的守护线程。该队列可以有从 servlet 线程添加到其中的对象。线程将等待一段时间并检查队列以查看其中是否有项目,如果有,则它将处理它们并删除它们。该线程需要在某个时间的某个地方启动。我在想,仅实现了 init 方法的 servlet 就可以完成此任务,或者是否有更好的地方可以将这样的启动代码放入应用程序服务器中?我处理这个问题的方式是不是很奇怪?
更新
我发现这个问题并且接受的答案是使用生命周期监听器。这是一种可移植的处理方式,还是我的代码将绑定到单个应用程序服务器。经过进一步的调查,我在留言板上发现了一些帖子,说我可以在 ServletContextListener 实现。
Abstract Question
What is the best way to load resources into memory that will be shared across servlets in a Java application server?
What I am actually doing
I want to create a daemon thread that monitors a queue. This queue could have objects added to it from servlet threads. The thread would wait until a set period of time and check the queue to see if it had items in it, if so then it would process them and remove them. This thread would need to be started somewhere at sometime. I was thinking that a servlet with only the init method implemented would work for this task or is there a better place to put startup code like this in an application server? Am I approaching the problem all wonky?
Updates
I found this question and the accepted answer was to use the LifeCycle Listener. Is this a portable way of doing things or is my code going to be tied to a single application server. A bit more investigation led me to a find a few posts on message boards saying that I could do this in a ServletContextListener implementation.
发布评论
评论(1)
我通常使用您描述的方法从 Servlet 间接启动这些类型的工作线程(通常它们存在于执行队列提取并控制处理的其他对象内)。
为了将对象从线程中拉出,您不需要根据时间来执行此操作,您可以让线程在队列对象上 wait() ,当某个其他线程将对象放入队列时,该线程将调用notify () 在队列上释放正在监视的“工作”线程。
谷歌“java工作线程等待通知”有很多例子。
I usually start these kinds of worker threads indirectly from a Servlet using the method you describe (usually they exist inside some other object that does the queue extraction and controls the processing).
For pulling objects off the thread, you don't need to do it based on time, you could have your thread wait() on the queue object and when an object is put onto the queue by some other thread, that thread would call notify() on the queue to release the watching 'worker' thread.
Google 'java worker thread wait notify' for many examples.