1

There is a requirement to detect the state of two objects, and the task needs to be real-time. The run method uses the while (flag) loop to end the life cycle of the thread by changing flag = false. The thread normally needs to run for 40 minutes or more. Using the thread pool will cause the core thread pool to run out, and the task will enter the queue, because each thread will run for 40 minutes The execution time of each thread is very long and not fixed, so there must be many threads that cannot respond in time.

I try to use new thread (runnable). Start() instead of using thread pool ThreadPoolExecutor.execute (runnable), but I think that this way, although I will cache runnable in a concurrent HashMap, I always feel that threads are not managed by the thread pool, and there may be exceptions (such as disappearing for no reason).

How to solve this problem, or what better way to replace the writing of while (flag).

Thank you for your advice, thank you!!!!!

my_project
  • 11
  • 1
  • Caching things yourself is often the precursor to memory leaks ... if you don't drop things out of the HashMap then whatever objects are still references by those `Runnable` can't be GC'd if you're still holding the HM.. Executor is orthogonal issue – Mr R Mar 19 '21 at 03:06
  • 1
    what is happening for that 40minutes - if you are waiting for results there are possibly better ways than allocating a thread and waiting - see https://stackoverflow.com/questions/14541975/whats-the-difference-between-a-future-and-a-promise for some examples / discussion on this. Because if you need to process 100x of those 40minute things "thread pool run-out" or even "thread run-out" is something you have to design for. – Mr R Mar 19 '21 at 03:07

1 Answers1

0

Using the thread pool will cause the core thread pool to run out, and the task will enter the queue,

If you use a Executors.newCachedThreadPool() a new thread will immediately get created if one is not available. The amount of time the jobs run is immaterial.

I always feel that threads are not managed by the thread pool, and there may be exceptions (such as disappearing for no reason).

You can certainly put the main processing body of your thread in a try { ... } catch (Exception e) { ... } block if you are worried about spurious exceptions – you can even do catch Throwable if necessary. When you submit(...) jobs to a thread-pool, that's what it does to protect the thread from an exception.

end the life cycle of the thread by changing flag = false

This flag should be volatile otherwise the changes between the threads will not be seen.

Gray
  • 115,027
  • 24
  • 293
  • 354