简体   繁体   中英

Killing a thread invoked asynchronously using executor service

I am trying to implement timeout for a thread which is invoked asynchronously by executor.

Process flow is like below:

Thread-1: Initiates a task to run on thread-2 using below code and returns immediately without waiting for Future object result

Thread-2: Long process and wil update some store some result in cache at end

Now, the requirement is to kill Thread-2 after some timeout value without blocking Thread-1

code snippet:

    ExecutorService executor = Executors.newFixedThreadPool(1);
    Future<Task> future = executor.submit(new Callable<Task>() {

        public Task call() throws Exception {
            try{

            return new Task();
            }catch (Exception e) {
            //print stack
        }

        }
    });

Any insight/suggestions to implement this?

See the following answer: https://stackoverflow.com/a/2733370/1299078

But depending on what Thread-2 does, you could let the thread end regularly, ie define a timeout on a http-request or a DB statement or if you have a loop, define an exit condition. this way you may end up with a more proper solution and you are able to properly release resources.

You can't do it using Java's ExecutorService because it doesn't expose any method to timeout and kill/complete/finish the newly spawned thread.

However, if you must do it then you can do it by directly using Thread class, below is high level approach:

  • From your main thread t1, spawn your worker thread t2 which is supposed to do your long work.
  • In your t1, you will have hold of the t2's ORV, pass it a new thread t3 along with time after which you want t2 to finish.
  • In t3 (you can also do this in t1 if you wish, but since you do not wish to block t1 so you need to have another thread to do this job), once that time has elapsed call t2.interrupt() , this will basically interrupt the t2 thread.
  • Now in t2, you will have to periodically keep on checking whether the thread is interrupted or not (using if (Thread.interrupted()) { ) and if it is interrupted then you can do whatever you want to do like - simply return therefore completing/killing/finishing the thread.

The basic ExecutorService does not provide a timeout functionality.

You could implement the timeout yourself like described by @hagrawal or you can use guava which has a very nice implementation for what you're asking for here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM