开发者

Java Threads calling methods on common Data Collector Object possible?

The idea: I have a JAX-RS webservice servlet (Object called webServle开发者_C百科t) which instantiates a data collecting Object dataCollector and passes this object on to multiple threads in their constructor. These threads query websites for results and then call the dataCollector.add(result) method to add the results to a Queue within the shared dataCollector.

I have two questions regarding this idea:

1) Can multiple threads call methods of a single shared object at the same time?

2) How does my webServlet object check when all threads are terminated to render a result page? Do I have to let my webServlet wait while all threads are running so I have a complete result list and how would I do that?


1) Yes, but perhaps not safely. In particular, if the queue in your dataCollector isn't a thread-safe queue like a ConcurrentLinkedQueue, you run the risk of a ConcurrentModificationException when a thread calls add() on it.

2) a) Use an ExecutorService (perhaps obtained from Executors) to submit Callables or Runnables. Keep the Futures that are returned and use get() to wait until he work is done.

b) You don't have to. The choice is up to you. If you send the response before the work is done, you obviously won't have a complete result yet.

c) See a).

If this is all new to you, you may want to check out Concurrency in the Java Tutorials.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜