在 Servlet 调用之外的 Java 应用程序服务器中启动线程或加载共享资源的最佳实践是什么?

发布于 2024-10-04 08:55:33 字数 686 浏览 3 评论 0 原文

抽象问题

将资源加载到将在 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一曲爱恨情仇 2024-10-11 08:55:33

我通常使用您描述的方法从 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文