-2

We are using a Scheduled in JAV that ExecutorService. Now, the problem is, we got this error: java.lang.OutOfMemoryError: unable to create new native thread

Currently, the logic that the Scheduled using is, everytime the Scheduled start (Only start when the previous Scheduled is completely finish), it will call ExecutorService.newFixedThreadPool(3), then execute these 3 threads.

Is the above error cause by this logic ? Im new at Java and MultiThreading also, really nead your help and thanks for reading!

Hoàng Huy
  • 31
  • 8
  • Without more detail, the best we can suggest that you do is read https://stackoverflow.com/questions/16789288. – Stephen C Jun 11 '23 at 06:43
  • If your code is as you described, then you should be OK. But I suspect that either you haven't described the code accurately, or it doesn't behave according to how you described it; e.g. because it is buggy. Having said that, if the code is as you describe, there is no need to create a new thread pool each time. If a scheduled task doesn't get started until the previous one ends, they can share the same thread pool. – Stephen C Jun 11 '23 at 07:13
  • 1
    _"everytime ... it will call ExecutorService.newFixedThreadPool(3), then execute these 3 threads"_ Do you shut down the thread pool after submitting the tasks? If not, you're leaking threads. Why do you create a new one each time and not reuse it instead? – Mark Rotteveel Jun 11 '23 at 07:54

1 Answers1

1

...everytime...it will call ExecutorService.newFixedThreadPool(3)...

That is not how thread pools are meant to be used!!

@MarkRotteveel almost answered your question in a comment above. Here's the rest:

Thread pools exist because creating and destroying threads is relatively expensive as compared to the cost of some of the tasks that you might want a thread to do. The purpose of a thread pool is to allow the program to re-use threads instead of continually creating new ones and then destroying them.* Instead of letting each "worker thread" die after it finishes its task, the thread pool keeps the workers alive, and waiting for you to submit more tasks.

Mark Rotteveel guessed—and it sounds like a good guess to me—that your program doesn't shut down the thread pools that it creates. So, every time it creates a new thread pool, it's also creating three new worker threads that will continue to live, taking up space, but doing nothing, until the program ends.

If that's true, then the fix is easy.

Create the thread pool just one time, and then periodically submit new tasks to the same pool object again and again.


* FYI, the same is true for any other kind of X pool that you might encounter in the future. Its purpose will be to let your program re-use objects of type X instead of continually creating and destroying them.

Holger
  • 285,553
  • 42
  • 434
  • 765
Solomon Slow
  • 25,130
  • 5
  • 37
  • 57