Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Can you explain short guide about background thread in 2021? I mean what is last recommendation to use, what was deprecated.
When I tried to found the information about it, I have confused. One place told about Thread, another Executor, the next about AsyncTask and so on. Every contains note or comment about obsolescence and not recommended by Google. What is true?
It really depends on what you are trying to do. Generally, the guide to background processing which was already linked by Dmitry in your comments is a good place to start.
Regarding the things you mentioned:
A Thread is useful if you have long-running tasks which do not happen all the time. Then you can create a thread whenever needed and it will be destroyed as soon as it's done executing.
By Executor I guess you are referring to the use of an ExecutorService. This is a class to manage a pool of threads. That is, you can give a job to the ExecutorService and it will assign it to any of its threads for execution. This is more efficient than creating a thread yourself every time, because the threads are not immediately destroyed after their work is complete. However, they will also stay in the memory because of that. Thus, an ExecutorService is suitable if you have short background jobs which occur often.
As for the AsyncTask, this API is indeed deprecated by now.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I am learning multithreading and am now confused about one topic i.e ExecutorService and CompletableFuture.
Let me summarise that what I learnt till now.
ExecutorService is a Java High-level thread API, which helps in managing threads, i.e two independent threads which is doing their task. But still, if threads are dependent then we can use producer-consumer patterns and many more.
This helps in achieving concurrency. Since multiple threads can be used for running a multiple tasks.
But In CompletableFuture, which we called async programming/ Reactive programming, is also used for accomplishing the same task. i.e It can also run multiple threads.
But I don't get the point of when to use which one and how they are different from each other? What are there use cases in which they sit perfectly?
A CompletableFuture is, in essence, a mechanism by which one thread can find out when another thread has finished doing something.
So, a typical model is this kind of method:
CompletableFuture<Result> doSomething() {
CompletableFuture<Result> future = new CompletableFuture<>();
... arrange to do work in some other thread ...
return future;
}
The caller of doSomething() gets back an object which it can use to determine completion, wait for completion, get the Result of doing 'something', and perhaps run some other work using the Result.
So, how does doSomething() arrange to do work in some other thread. Well, one way is to execute the work vis some ExecutorService. Though there are plenty of other ways to go about it. Regardless, when the work is complete, it will call future.complete(someResult) to set the CompletableFuture into 'completed' state with the expected Result.
Maybe you're confused because our caller could write
doSomething().thenAcceptAsync((result) -> blahBlah(result));
In this case, doSomething() proceeds as above. When that is complete, we want to run another operation, also asynchronously. Because we used theAcceptAsync, this work will be handled via an ExecutorService known to the CompletableFuture framework (the common ForkJoinPool, to be exact - this is documented).
Summary - this is not 'choose one or the other'. ExecutorServices provide the means to run units of work in other threads. CompletableFutures provide the means to know and react to completion of those units of work.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Aside from the properties to know the state of the task and the call backs (completed, failed, etc), is there any other differences of using JavaFX Task over a plain old Java Thread with a lambda?
I'm not asking what's good or bad, I'm not asking what you think I should do, I'm asking for the objective factual differences that would happen when using a Task instead of a plain lambda to run a background thread in a JavaFX application. Aside from the the differences that I already mentioned.
On the Oracel's tutorial for concurrency, in the section titled "Why Use the javafx.concurrent Package?" it says:
If you have special requirements or need extra power over the code, implementing a background worker by creating a Runnable object and a new thread is an appropriate way to go.
other than that, all the reasons for using a Task are equally applicable to a Runnable and I don't see what special requirements or extra power one gains, I also don't see what you lose, if anything, aside from state and callbacks, when choosing Runnable over Task. What I do see is that using Task is much more verbose:
new Thread(this::doSomething).start();
vs
new Thread(new Task<Void>() {
#Override
protected Void call() throws Exception {
doSomething();
return null;
}
}).start();
My concern would be the some unexpected side effect from choosing a shorter more concise version of the code that according to Oracle, should only be used in special cases.
doSomething is a variety of different activity on this example and I'm interested in facts that are agnostic to what they do. In my case, it's mostly network requests that then update the UI by using Platoform.runLater.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm developing a java 2D game, with a Board class and Mob(s) class. The board class has a thread that calls 'repaint()' every a specified delay, while the mobs class constructs a new thread for each of the mob spawned, which means when it does something, it ticks its time on its own. Simply said, I seperate the thread to enable frame rate setting. So i just need to only set how long does the Board thread sleep, like faster sleep means more frame rate (I use threads for this because a site says threaded timing can be made real precise). But then it means in a crowded in-game situation there would be a lot of thread running from every active Mob there.
My question: if i have this lots of thread running at the same time, wouldn't it be consuming a lot of system resources? And if yes, what is the best way round so I don't need to use threads? (just to note 2D game "crowded" situation can be "really crowded").
I think your question could resume to one of these :
Why is creating a Thread said to be expensive?
How expensive is creating of a new thread in Java? When should we consider using of a thread pool?
Is it expensive to create the Thread object or to actually start the thread?
etc...
Plenty of resource to find info on the subject.
what is the best way round so I don't need to use threads
This question is not appropriate for SO (too broad)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I've been watching a lot of videos on data structures, and these terms are always being mentioned: synchronized/not synchronized and thread-safe/not thread-safe.
Can someone explain to me in simple words what synchronized and thread-safe mean in Java? What is sync and what is thread?
A thread is an execution path of a program. A single threaded program will only have one thread and so this problem doesn't arise. Virtually all GUI programs have multiple execution path and hence threads - one for processing the display of the GUI and handing user input, others for actually performing the operations of the program. This is so that the UI is still responsive while the program is working.
In the simplest of terms threadsafe means that it is safe to be accessed from multiple threads. When you are using multiple threads in a program and they are each attempting to access a common data structure or location in memory several bad things can happen. So, you add some extra code to prevent those bad things. For example, if two people were writing the same document at the same time, the second person to save will overwrite the work of the first person. To make it thread safe then, you have to force person 1 to wait for person 2 to complete their task before allowing person 1 to edit the document.
Synchronized means that in a multiple threaded environment, a Synchronizedobject does not let two threads access a method/block of code at the same time. This means that one thread can't be reading while another updates it.
The second thread will instead wait until the first is done. The overhead is speed, but the advantage is guaranteed consistency of data.
If your application is single threaded though, Synchronized has no benefit.
As per CIP:
A class is thread-safe if it behaves correctly when accessed from
multiple threads, regardless of the scheduling or interleaving of the
execution of those threads by the runtime environment, and with no
additional synchronization or other coordination on the part of the
calling code.
So thread safety is a desired behavior of the program in case it is accessed by multiple threads. Using the synchronized block is one way of achieving that behavior. You can also check the following:
What does 'synchronized' mean?
What does threadsafe mean?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How can I know when the thread was stoped and the processor moves to another thread..
Transition between threads harms my calculations, there is some way to know if the thread left and returned to my function?
You can not know when your thread was stopped and the system rescheduled another thread.
But - you can minimize the number of times this event happens by setting the affinity of your thread to one of the processors, and the affinities of the other threads to the other processors.
If you are using Linux, you can use taskset for each thread in the system (get the list by "ps -e") to set the affinities of the other threads to other processors.
This will decrease the load on the processor and will cause it to context-switch less times.
The simple answer is - you can't. Even if you could detect thread context switches it happens far too often to usefully logged.
A better question would be to look at why you need to know. If there is a problem there post it as a question and we can solve the real issue.