Dan Koshmaro
Dan Koshmaro

Reputation: 53

Run timer without thread in java

I am building simulator that run 1000(and more) clients, in each client i want to run task after X time, i tried TimerTask, the problem is that in each task(more than 1000) new thread is created.

Did there as any task timer without thread?

Upvotes: 2

Views: 534

Answers (2)

Niklas P
Niklas P

Reputation: 3507

If you want to simulate 1000(and more) clients acting simultaneously, you have to use Threads! Otherwise you would have a single Thread in which your definite logic specifies when what logic of what client is done - that really does not simulate the clients acting in parallel.

Upvotes: 0

Andreas
Andreas

Reputation: 159086

You can schedule multiple TimerTasks using a single Timer, they just can't run at the same time. Depending on your need, that may be good enough.

But, quoting the javadoc of Timer:

Java 5.0 introduced the java.util.concurrent package and one of the concurrency utilities therein is the ScheduledThreadPoolExecutor which is a thread pool for repeatedly executing tasks at a given rate or delay. It is effectively a more versatile replacement for the Timer/TimerTask combination, as it allows multiple service threads, accepts various time units, and doesn't require subclassing TimerTask (just implement Runnable). Configuring ScheduledThreadPoolExecutor with one thread makes it equivalent to Timer.

Upvotes: 4

Related Questions