Why use Looper/Handler when I could use an Executor method(s)?
The Looper/Handler duo seems rather clunky and doesn't seem to do a great deal beyond allowing the queuing of runnables and seemingly has less flexibility.
What was the looper design rationale?
Thanks.
A looper by itself does not have many advantages over an executor. It is how Android manages worker. But you are able to get the main thread of your app with Looper.getMainLooper(), this can have the following advantages:
You can change the ui from the MainLooper, (only do if not a compute intense background task, since you would freeze the UI)
Execute Runnables "in-sync" with the all the other native tasks. Meaning you post your Runnable in the same queue as android does
No need to create a thread yourself. You can use the already running Looper.
Related
while learning the difference between multi-threading and Concurrency.i follow this stackoverflow answer
according to my understanding AsyncTask is just used to on or off the use of main thread{ui thread} while events like http request or fetching data from database. and after task is done main thead is reallocated to the event by AsyncTask task.
but Android Official says "An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread"
now i am confused.
android use multi-theading its just wrapper class for thread management.
C# async and await is diffrent concept.
An AsyncTask "touches" two threads: Main/UI and the Background one. There are few of its methods that run on Main/UI Thread (onPre/onPostExecute()) and one method that is run on a WorkerThread in background. There is an internal sync/queue between those methods.
Concurrency (async/await) doesn't (necessarily) use a second thread but uses "moments of when the CPU is free". Think about this non-real case: if the Main/UI Thread is 100% busy then no any Concurrency could be executed until the Main/UIThread has a bit of "free CPU cycles" to share. Intead, in this last example AsyncTasks will do its job asynchronously without take in count other Threads (and its results will be queued to UI/MainThread to be processed later).
Since I'm trying to understand a few of the new features provided in Java 8, I came upon the following situation:
I wish to implement asynchron method calls into my application (in JavaFX). The idea was to provide/use a seperate thread for everything related to the GUI so that background tasks wont block/delay the visible output in my application.
For the background tasks, I thought about either use a pool of threads or simply run them in the main thread of the application for now. Then, I came upon the ForkJoinPool used in the standard way by using the CompletableFuture class when doing something like this:
CompletableFuture.runAsync(task);
whereas task is a Runnable.
In most tutorials and the Javadoc, the ForkJoinPool is described as "a pool which contains threads waiting for tasks to run". Also, the ForkJoinPool is usually the size of the cores of the users machine, or doubled if hyperthreading is supported.
What advantages does the ForkJoinPool give me over the traditional Thread when I want to run a task asynchronously?
ForkJoinPool is not comparable with Threads, it's rather comparable with ThreadPools. Creating a new thread by code often bad and will lead to OutOfMemoryErrors because it is not controlled. Depending on your use case you might need to use a ForkJoinPool or a different pool but make sure you use one. And by the way, all CompletableFuture methods have overloads that allow you pass your own thread pool.
Some benefits of ForkJoinPool,
Already initialised for you and shutdown on the JVM shutdown, so you don't need to worry about that
Its size can be controlled through a VM parameter
Its perfect for compute bound task where work stealing can be beneficial, although this could be a problem depending on the case.
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.
This question already has answers here:
When should we use Java's Thread over Executor?
(7 answers)
Closed 7 years ago.
In Java, both of the following code snippets can be used to quickly spawn a new thread for running some task-
This one using Thread-
new Thread(new Runnable() {
#Override
public void run() {
// TODO: Code goes here
}
}).start();
And this one using Executor-
Executors.newSingleThreadExecutor().execute(new Runnable(){
#Override
public void run() {
// TODO: Code goes here
}
});
Internally, what is the difference between this two codes and which one is a better approach?
Just in case, I'm developing for Android.
Now I think, I was actually looking for use-cases of newSingleThreadExecutor(). Exactly this was asked in this question and answered-
Examples of when it is convenient to use Executors.newSingleThreadExecutor()
Your second example is strange, creating an executor just to run one task is not a good usage. The point of having the executor is so that you can keep it around for the duration of your application and submit tasks to it. It will work but you're not getting the benefits of having the executor.
The executor can keep a pool of threads handy that it can reuse for incoming tasks, so that each task doesn't have to spin up a new thread, or if you pick the singleThread one it can enforce that the tasks are done in sequence and not overlap. With the executor you can better separate the individual tasks being performed from the technical implementation of how the work is done.
With the first approach where you create a thread, if something goes wrong with your task in some cases the thread can get leaked; it gets hung up on something, never finishes its task, and the thread is lost to the application and anything else using that JVM. Using an executor can put an upper bound on the number of threads you lose to this kind of error, so at least your application degrades gracefully and doesn't impair other applications using the same JVM.
Also with the thread approach each thread you create has to be kept track of separately (so that for instance you can interrupt them once it's time to shutdown the application), with the executor you can shut the executor down once and let it handle its threads itself.
The second using an ExecutorService is definitely the best approach.
ExecutorService determines how you want your tasks to run concurrently. It decouples the Runnables (or Callables) from their execution.
When using Thread, you couple the tasks with how you want them to be executed, giving you much less flexibility.
Also, ExecutorService gives you a better way of tracking your tasks and getting a return value with Future while the start method from Thread just run without giving any information. Thread therefore encourages you to code side-effects in the Runnable which may make the overall execution harder to understand and debug.
Also Thread is a costly resource and ExecutorService can handle their lifecycle, reusing Thread to run a new tasks or creating new ones depending on the strategy you defined. For instance: Executors.newSingleThreadExecutor(); creates a ThreadPoolExecutor with only one thread that can sequentially execute the tasks passed to it while Executors.newFixedThreadPool(8)creates a ThreadPoolExecutor with 8 thread allowing to run a maximum of 8 tasks in parallel.
You already have three answers, but I think this question deserves one more because none of the others talk about thread pools and the problem that they are meant to solve.
A thread pool (e.g., java.util.concurrent.ThreadPoolExecutor) is meant to reduce the number of threads that are created and destroyed by a program.
Some programs need to continually create and destroy new tasks that will run in separate threads. One example is a server that accepts connections from many clients, and spawns a new task to serve each one.
Creating a new thread for each new task is expensive; In many programs, the cost of creating the thread can be significantly higher than the cost of performing the task. Instead of letting a thread die after it has finished one task, wouldn't it be better to use the same thread over again to perform the next one?
That's what a thread pool does: It manages and re-uses a controlled number of worker threads, to perform your program's tasks.
Your two examples show two different ways of creating a single thread that will perform a single task, but there's no context. How much work will that task perform? How long will it take?
The first example is a perfectly acceptable way to create a thread that will run for a long time---a thread that must exist for the entire lifetime of the program, or a thread that performs a task so big that the cost of creating and destroying the thread is not significant.
Your second example makes no sense though because it creates a thread pool just to execute one Runnable. Creating a thread pool for one Runnable (or worse, for each new task) completely defeats the purpose of the thread-pool which is to re-use threads.
P.S.: If you are writing code that will become part of some larger system, and you are worried about the "right way" to create threads, then you probably should also learn what problem the java.util.concurrent.ThreadFactory interface was meant to solve.
Google is your friend.
According to documentation of ThreadPoolExecutor
Thread pools address two different problems: they usually provide
improved performance when executing large numbers of asynchronous
tasks, due to reduced per-task invocation overhead, and they provide a
means of bounding and managing the resources, including threads,
consumed when executing a collection of tasks. Each ThreadPoolExecutor
also maintains some basic statistics, such as the number of completed
tasks.
First approach is suitable for me if I want to spawn single background processing and for small applications.
I will prefer second approach for controlled thread execution environment. If I use ThreadPoolExecutor, I am sure that 1 thread will be running at time , even If I submit more threads to executor. Such cases are tend to happen if you consider large enterprise application, where threading logic is not exposed to other modules. In large enterprise application , you want to control the number of concurrent running threads. So second approach is more pereferable if you are designing enterprise or large scale applications.