Search code examples
javamultithreadinggarbage-collection

Too many Garbage collection threads


I am developing a software with java, it creates a thread upon receiving an event (from sensors). the time-to-live of these threads is very small (< 1 second)
The sensor sends maximal 10 events/minute. This app works fine for most of the time. but sometime it hangs.
When looking at the eclipse debugger, I find out that there are to many threads and most of them are "Thread[garbage collected]" (about 800 threads @_@)

I don't know if that bug is caused by dynamic-creating-threads in my code or other bugs?

EDIT:
The problem is indeed caused by creating too many threads. I have logged all sensor's events with timestamp and there are some points it creates about 1200 events/minute (damn!).
I also wrote a small java program which creates as many threads as posible. At ~4100th thread (well, wooden computer) , jvm crashes. It does not hangs like my app does :-?.
Therefore I suppose that there are (maybe) rare conditions while creating threads dynamically and it causes the garbage collection threads hang?

enter image description here


Solution

  • Don't create a new thread for each event that is received. Instead, use the classes from the java.util.concurrent package.

    Create an ExecutorService (using one of the static methods in class Executors) and submit jobs for handling events to the ExecutorService. The ExecutorService is a thread pool that manages the threads for you.