R
R
Renat Iliev2014-10-09 15:15:14
Java
Renat Iliev, 2014-10-09 15:15:14

How to limit the running time of a thread?

I create a server in Java, each client has its own thread, I use the ExecutorService class to create and manage threads.
But the trouble is that some requests from the client can take too long, or even hang while waiting for a response from third-party servers (this is rare, but it happens). To get rid of this problem, I decided to delete the thread by timeout so as not to clog the thread pool, but how to implement this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanKiLL, 2014-10-09
@IzeBerg

In the ExecutorService, threads are reused in this and the whole point of these pools.
Each task that you throw, for example Runnable, gets into the queue and then is executed by the executor when some thread is free.
If you look at the names of the threads in the executor, they will be something like this pool-2-thread-4
You can reach the thread in which your code is running, you can directly from Runnable or Callable, depending on what you feed the executor'y there
If you want to interrupt the thread for some reason, then something like this.
Thread.currentThread().interrupt();

B
bimeg, 2014-10-09
@bimeg

Use connection timeout - if it takes a long time to score on the client. Or NIO - there you can process the connection without blocking (and as a bonus, you can start one thread for several clients).

B
bromzh, 2014-10-09
@bromzh

You can run these tasks asynchronously. The loop or executor must have a function to start a task with a timer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question