0

I have completed the following Java Servlet construction: [I believe the main idea is that of consumer-producer]

  1. A Java servlet that receives multiple http POST requests

  2. It puts all requests into a Queue [ConcurrentLinkedQueue]

  3. All requests in the Queue are processed by a single and independent thread (like an engine). This thread works independently of the servlets. There is a good reason for the separate thread, since I need data from several and different http requests to do the processing. The Queue waits until it has enough requests and then starts the processing.

Now I'm in the final step: Once e.g. http request No1 has been processed by the independent thread engine, I need to notify the specific servlet thread (e.g. No1) where it came from so that I can reply, i.e. send the response back to the corresponding client.

How do I solve this threading issue? How can the single thread engine notify the correct servlet thread each time? How should I code this?

4

3 回答 3

2

我不知道这些要求是从哪里来的,但是还有其他几种更简单的方法来解决这个问题:

  • 使用ExecutorService. 只需将任务提交到池并阻止返回的Future对象。非常简单有效。一旦您的任务准备就绪,Future.get()将返回结果

  • 使用 Servlet 3.0,您可以将整个处理放在异步线程中。这更具可扩展性。基本上你正在提交一个任务并立即释放 HTTP 线程。异步线程不仅处理该队列中的项目,还通过AsyncContext对象返回 HTTP 响应。

如果您确实需要使用队列和单独的线程,请查看 Java条件。但这是更多的低级工作。

于 2012-07-22T13:44:12.170 回答
1

使用SingleThreadExecutor。让您的 servlet 创建 Callable 对象并将它们提交给执行程序,然后调用get()返回的 Future:

Callable<Foo> callable = new Callable<Foo>() {
    // TODO implement call();
};
Future<Foo> future = executor.submit(callable);
Foo result = future.get();
于 2012-07-22T13:44:31.683 回答
0

是否有充分的理由让您在单独的线程中有一个队列来执行工作?如果 servlet 需要等待处理结果才能向客户端返回响应,那么为什么不在同一个线程中执行处理并同步返回结果呢?

如果您真的想异步执行操作,您可以使用Future对象来检查计算的完成状态,并获取其结果。

于 2012-07-22T13:42:39.093 回答