开发者

How to get the main thread in java?

开发者 https://www.devze.com 2023-03-09 07:33 出处:网络
So I have a long running process that I want to encapsulate as a Runnable and dispatch it in a thread. To be more specific, I have a POST web service that creates a file in the file system but the cre

So I have a long running process that I want to encapsulate as a Runnable and dispatch it in a thread. To be more specific, I have a POST web service that creates a file in the file system but the creation of the file can tak开发者_开发技巧e a very long time.

In the resource method of my web service, I want to be able to dispatch a thread to do the file creation and return the status 200. I don't think I can just do Thread.join because this would mean that the current thread would have to wait for the file creation thread to finish. Instead, I want to join the file creation thread to the main thread. Question is, how do I get the main thread in java?


I am not sure whether I get you right. Here is what I understood:

You want to preform a possibly long running operation (file creation) you do not want you service method to block while that task is exectued you want the task executed in a thread that exists outside the boundary/lifetime of the single request.

Am I right so far?

If sou really recommend you look into the newer concepts in java.util.concurrent. The concepts described there should give you enogh information tackkle this

Basic credo: Don't think in threads, think in tasks.

General Book recommendation: Java Concurrency in Practice by Brian Goetz


You will need to process the request asynchronously. A separate thread will be created for doing the heavy work and the request receiving thread will be free to process other requests. Please checkout following articles.

  • Asynchronous processing in Servlet 3.0
  • Asynchronous support in Servlet 3.0 spec
  • Asynchronous Support in Servlet 3.0


When you spawn the file-creation thread, you need to pass it some kind of reference to the parent thread, so it can communicate back (i.e. you provide something to enable a callback).

This could be the actual Thread object (obtained using Thread.currentThread, as someone said in a comment) or some other object that you use to signal when the file-creation thread is done.

0

精彩评论

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