Can I ask a rookie Java question?
I am downloading some files from the web. This method download(url location) is called multiple times.
public static void download(final String url) {
Thread t = new Thread("download") {
@Override
public void run() {
try {
synchronized (object) {
// download & save
}
} catch(Exception e) {}
}
};
t.start();
}
I added “synchronized” so that downloads happens one-by-one. (not multiple downloads occur at the same time).
I am guessing even though download() is called multiple times, synchronized will block other threads until the first thread is finished.
Will above code work? or do I have to implement Queue? and dequeue one-by-one?
Can synchronized block “enough” threads? (30? 50?) or does it have limits?
Yes, as long as
objectrefers to the same object in all threads, the code in the synchronized block will only be executed by one thread at a time.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.
No, no limits. At least not near 30 or 50 🙂