I have a program for which I plan to use a lot of Timer objects, and as I understand it each Timer runs on it’s own thread. So I wondered if it’s possible to start so many Timers that it hurts the performance of the program with too many threads.
For example, I was thinking of having several (boolean, Timer) pairs to have booleans that invert at several different time intervals.
Yes,
Timerobjects do consume thread resources, so it is possible to hit a limit within the JVM. If your goal is to schedule tasks to run at various points in time, you might want to look at one of the many Java ExecutorService implementations such as ScheduledThreadPoolExecutor. The Executors class provides a convenient factory for generating these objects. Several implementations utilize thread pools, which you can configure to determine how many tasks may run simultaneously. You can also consume output that the tasks produce (if any) and shutdown the tasks in an orderly fashion if your program needs to exit.