Search code examples
javapool

Should I use Thread Pool instead pool in my situation?


I have simple Tower Defence game. Every monster moves in it's own thread so when new wave comes about 20 new threads are done (from 10 to 25, randomly). I remember something like executor class which is useful in situations when there are many-short lived threads. Like I have. So my questions are:

  1. Should I use thread pool and how much would it increase perofrmance?
  2. How should I implement it? Should pool be a field?

Solution

  • I think it is safe to assume that the interval between waves is more than one second, isn't it? Otherwise, your game would be quite hard to beat. ;-)

    I would not expect that using a thread pool will make a difference if you spawn so few threads (15-25 threads are not a big deal). Personally, I would just use new Thread. You can always switch to an ExecutorService later, but I don't think it is needed in your scenario.

    A thread pool is reasonable when you are writing, for example, a web server that has to process several hundred of incoming requests (assuming that each request should be handled in a separate thread). Then a thread pool will likely increase performance but its most important advantage is that it is a handy way to limit resource usage.

    Why? If you would just spawn a new thread on each request, you risk that you will soon run out of resources if there are many requests at the same time. Using a thread pool with an upper limit of threads prevents that from happening.

    (However, without knowing the details of your application, from a pure design perspective, avoiding threads completely and keeping all the game logic in one thread is definitely something that you should consider. It will make things much simpler. But again, I don't have the details.)