HahaHortness
HahaHortness

Reputation: 1628

Can I saturate a program with Timer objects?

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.

Upvotes: 4

Views: 394

Answers (2)

jtahlborn
jtahlborn

Reputation: 53694

You can run more than one task on the same Timer. Depending on how cpu intensive the tasks are, you could use just one or a few Timer instances to manage all your tasks. or, as @Rob mentions, you can use a ScheduledThreadPoolExecutor.

Upvotes: 1

Rob H
Rob H

Reputation: 15020

Yes, Timer objects 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.

Upvotes: 4

Related Questions