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, 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.
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.
Related
Is this possible to run multithreaded Java application in a deterministic fashion? I mean to have always the same thread switching in two different runs of my application.
Reason for that is to run simulation in exactly the same conditions in every run.
Similar case is when one gives some arbitrary seed when using random number generator to obtain always the same "random" sequence.
I am not aware of any practical way to do this.
In theory, it would be possible to implement a bytecode interpreter with an entirely deterministic behavior under certain assumptions1. You would need to simulate the multiple threads by implementing the threads and the thread scheduling entirely in software and using a single native thread.
1 - For example, no I/O, and no use of the system clock.
No it is not possible (other than to simulate it yourself) to use multiple threads interleaving in the same way each time around. Threads are not designed to do that.
If you want deterministic results, don't use threads.
As quoted by OldCurmudgeon, it's not possible with multi threading.
If you decide to use single Thread, I prefer newSingleThreadExecutor to normal Thread due to flexibility and advantages of newSingleThreadExecutor
Use
newSingleThreadExecutor from Executors
public static ExecutorService newSingleThreadExecutor()
Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.)
Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.
Related SE questions:
Difference between Executors.newFixedThreadPool(1) and Executors.newSingleThreadExecutor()
ExecutorService vs Casual Thread Spawner
I have only two short-lived tasks to run in the background upon the start of the application. Would it make sense to use a thread for each task or an Executor, for instance, a single thread executor to submit these two tasks.
Does it make sense to create two threads that die quickly as opposed to having a single threaded executor waiting for tasks throughout the lifecycle of the application when there are none?
One big benefit of using a threadpool is that you avoid the scenario where you have some task that you perform repeatedly then, if something goes wrong with that task that causes the thread to hang, you're at risk of losing a thread every time the task happens, resulting in running the application out of threads. If your threads only run once on startup then it seems likely that risk wouldn't apply to your case.
You could still use Executor, but shut it down once your tasks have both run. It might be preferable to use Futures or a CompletionService over raw threads.
If you do this more than once in your application, ThreadPoolExecutor is definitely worth a look.
One benefit is the pooling of threads. This releaves the runtime to create and destroy OS objects every time you need a thread. Additionally you get control of the amount of threads spawned - but this seems not the big issue for you - and threads running/done.
But if you actually really only spawn two threads over the runtime of your application, the executors may be oversized, but they are nevertheless very comfortable to work with.
Since Nathan added Futures, there is also Timer and TimerTask. Also very convenient for "Fire and Forget" type of background action :-).
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?
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.
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.
Could please somebody tell me a real life example where it's convenient to use this factory method rather than others?
newSingleThreadExecutor
public static ExecutorService newSingleThreadExecutor()
Creates an Executor that uses a single worker thread operating off an
unbounded queue. (Note however that if this single thread terminates
due to a failure during execution prior to shutdown, a new one will
take its place if needed to execute subsequent tasks.) Tasks are
guaranteed to execute sequentially, and no more than one task will be
active at any given time. Unlike the otherwise equivalent
newFixedThreadPool(1) the returned executor is guaranteed not to be
reconfigurable to use additional threads.
Thanks in advance.
Could please somebody tell me a real life example where it's convenient to use [the newSingleThreadExecutor() factory method] rather than others?
I assume you are asking about when you use a single-threaded thread-pool as opposed to a fixed or cached thread pool.
I use a single threaded executor when I have many tasks to run but I only want one thread to do it. This is the same as using a fixed thread pool of 1 of course. Often this is because we don't need them to run in parallel, they are background tasks, and we don't want to take too many system resources (CPU, memory, IO). I want to deal with the various tasks as Callable or Runnable objects so an ExecutorService is optimal but all I need is a single thread to run them.
For example, I have a number of timer tasks that I spring inject. I have two kinds of tasks and my "short-run" tasks run in a single thread pool. There is only one thread that executes them all even though there are a couple of hundred in my system. They do routine tasks such as checking for disk space, cleaning up logs, dumping statistics, etc.. For the tasks that are time critical, I run in a cached thread pool.
Another example is that we have a series of partner integration tasks. They don't take very long and they run rather infrequently and we don't want them to compete with other system threads so they run in a single threaded executor.
A third example is that we have a finite state machine where each of the state mutators takes the job from one state to another and is registered as a Runnable in a single thread-pool. Even though we have hundreds of mutators, only one task is valid at any one point in time so it makes no sense to allocate more than one thread for the task.
Apart from the reasons already mentioned, you would want to use a single threaded executor when you want ordering guarantees, i.e you need to make sure that whatever tasks are being submitted will always happen in the order they were submitted.
The difference between Executors.newSingleThreadExecutor() and Executors.newFixedThreadPool(1) is small but can be helpful when designing a library API. If you expose the returned ExecutorService to users of your library and the library works correctly only when the executor uses a single thread (tasks are not thread safe), it is preferable to use Executors.newSingleThreadExecutor(). Otherwise the user of your library could break it by doing this:
ExecutorService e = myLibrary.getBackgroundTaskExecutor();
((ThreadPoolExecutor)e).setCorePoolSize(10);
, which is not possible for Executors.newSingleThreadExecutor().
It is helpful when you need a lightweight service which only makes it convenient to defer task execution, and you want to ensure only one thread is used for the job.
There seem to be a number of different ways in which one can create threads (Runnable vs Thread class) and also ThreadPools.
Are there any difference in terms of efficiency and which are the most efficient (in terms of performance) techniques for creating and pooling threads in Java?
If you need to handle many short and frequent requests it is better to use a ThreadPool so you can reuse threads already open and assign them Runnable tasks.
But when you need to launch a thread for a single task operation or instantiate a daemon thread that run for all the application time or for a long specific time then could be better create a single thread and terminate it when you don't need it anymore.
At the end of the day, they're all relying on the same underlying Thread-based mechanism to actually do the work. That means that if you are asking "what is the most efficient way to start a single thread?" the answer is, create a Thread object and call start() on it, because any other method will take some other steps before it eventually creates a Thread object and calls start() on it.
That doesn't mean that this is the best way to spawn threads, it just means that it is the most low-level way to do it from Java code. What the other ways to create threads give you is different types of infrastructure to manage the underlying Threads, so your choice of method should depend on the amount and kind of infrastructure you need.