0

In my example I have:

Task - does some long running operations in background thread: looping over large data set and do some other heavy operations for each item.

TaskExecutor - put Task to execute in background Thread from ThreadPool.

Caller - client requests TaskExecutor to start, pause and resume Task at some point.

class TaskExecutor {
    val threadPool = Executors.newFixedThreadPool(1) as ThreadPoolExecutor

    // begin API methods section
    fun submitTask() {
        threadPool.submit(Task())
    }

    fun pauseThreadPool() {
        // pause all threads (in this example just one thread) in threadPool
    }

    fun resumeThreadPool() {
        // resume all threads (in this example just one thread) in threadPool
    }
    // end API methods section

    fun runTask() {
        for(item in items) {
            // do something with item
        }

    }

    inner class Task(): Runnable {
        override fun run() {
            runTask()
        }           
    }
}
class Caller() {
    val taskExecutor = TaskExecutor()
    taskExecutor.submitTask()
    ...
    ...
    taskExecutor.pauseThreadPool()
    ...
    ...
    taskExecutor.resumeThreadPool()
}

Question: is there any possibility to pause ThreadPool(or Thread from ThreadPool) and resume it by Caller to call pauseThreadPool() and resumeThreadPool() functions when it needs. Expected time for ThreadPool to be on pause is up to a few minutes.

devger
  • 703
  • 4
  • 12
  • 26
  • fantaghirocco, did you try that? I tried accepted solution from the question you shared and it doesn't work for me, thread is not pausing with that solution. That is why i asked this question. – devger Dec 24 '21 at 16:30
  • 1
    I may be wrong, but I doubt it is possible to anyhow pause threads. You need to implement this at the tasks level. If I understand mentioned example properly, it pauses starting of new tasks, but it doesn't pause already running tasks. – broot Dec 24 '21 at 17:26
  • broot, ohh..I see your point. I think you are right, yes, I've just tested, it pauses starting of new tasks(runnable/thread) in threadpool, but not the current which is running now and has been submitted before the pause. In my scenario I need to pause already submitted and running task. Correct, I can do pause at the task level(in for loop, etc.), but I was thinking if pause can be done for the whole Thread, like sleep(), but in more better approach. – devger Dec 24 '21 at 18:35

0 Answers0