Reputation: 3540
I'm having a util class where I'm trying to write to secure setting like,
public static void putIntInSS(final ContentResolver resolver, final String key,
final int value) {
new Thread(new Runnable() {
@Override
public void run() {
Settings.Secure.putInt(resolver, key, value);
}
}).start();
}
When this new Thread()
would be GC'ed? Is it good to use new Thread()
in my application instead of Handler
? If there is some disadvantage of using threads in this way what are they?
Upvotes: 0
Views: 114
Reputation: 5042
Your thread will become a candidate for GC just as soon as it finishes. See here.
"Is it good to use new Thread() in my application instead of Handler?"
In a word, "no". You should make sure you understand all the pros & cons of multithreading, and proper concurrency techniques, before you start putting extra threads in production code. It's hard to overstate the elegance of a message-based queueing system (e.g., Handler
), especially for message-driven UI based apps (Android, Windows). A Handler
is an effective way of creating the illusion of concurrency, even if it is limited to the throughput of a single thread.
"some disadvantage of using threads in this way..."
Well, there are a lot. I'll go ahead and get the list started:
The above mentioned problems will become acute if you start many operations like this in a short time span. Furthermore:
A lot of software engineering is about how to avoid unnecessary complexity. Keep things simple. Sometimes you're gonna have demanding performance requirements; those projects require careful planning and a detailed understanding of how a CPU works. Most of the time, the most important thing about a piece of software is that it's correct. And for that, it's easier to stay single-threaded.
Upvotes: 1