Java/android: Synchronized Vs Queue Implementation
Solution 1:
Here's how to do it:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
publicclassQueueDownloader {
privatefinalExecutorServiceexecutor= Executors.newSingleThreadExecutor();
publicvoiddownload(final String url) {
executor.execute(newRunnable() {
@Overridepublicvoidrun() {
// download & save
}
});
}
}
This will queue all runnables (i.e. downloads) on a single background-thread.
Solution 2:
Will above code work?
Yes, as long as object
refers to the same object in all threads, the code in the synchronized block will only be executed by one thread at a time.
[...] or do I have to implement Queue? and dequeue one-by-one?
Generally speaking I would recommend you to use as high-level constructs as possible (for instance from the java.util.concurrent package). You may for instance consider using an executor service for these types of things.
[...] Can synchronized block "enough" threads? (30? 50?) or does it have limits?
No, no limits. At least not near 30 or 50 :-)
Solution 3:
If you can avoid creating additional threads, you should generally do so. As I understood it, you never want two work items (downloads) in parallel, so the best idea, performance-wise, is using a concurrent queue implementation that is polled by a single worker thread.
Post a Comment for "Java/android: Synchronized Vs Queue Implementation"