Java/Android: Synchronized Vs Queue Implementation
Solution 1:
Here's how to do it:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class QueueDownloader {
private final ExecutorService executor = Executors.newSingleThreadExecutor();
public void download(final String url) {
executor.execute(new Runnable() {
@Override
public void run() {
// 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 :-)
- Handle Multiple Infinite Tasks In A Single Thread? P.s Run One Task At A Time And Control Its Task Behavior(i.e Starting/stoping Task) From Outside
- Can An Android Asynctask Doinbackground Be Synchronized To Serialize The Task Execution?
- Java ,properly Using Static Variables To Prevent Deadlock - Synchronizing
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"