I make multiple web requests from an Android application I'm working on. I want all these requests to be processed one at a time in the order they arrive, does my below code do that?
The way I read and understand synchronized is that of all the threads I spin off, only one can be in any of the below methods at one time. For example, if a user tries to postPhoto in one thread and then immediately getData in another thread, the getData thread will have to wait until the postPhoto thread is finished before it starts getting data. Since all my web requests go through this class and all the methods are synchronized, that means they're essentially queued up correct?
public class Controller {
public synchronized static String getData(String url, String limit) { ... }
public synchronized static String postPhoto(String filepath, int server_id) { ... }
public synchronized static InputStream getPhoto(String thumbnailPath) { ... }
public synchronized static String createIncident(String name, String description) { ... }
public synchronized static String updatePerson() { ... }
synchronized static boolean verifyConnection(String response) { ... }
}
EDIT:
I probably should have mentioned that even though some of the above methods are called createIncident or updatePerson, all of them ONLY make httprequests, the code inside all of the methods is generally the same except for important minor variations. In other parts of my code, I spin off threads to call these methods, and that's the part I was asking about. Since those threads call these methods, thread B that is calling getData will have to wait until thread A finishes it's part of postPhoto.
It depends on your implementation as well. Is your controller singleton or instance per thread? do your methods use shared objects?
If singleton and methods sharing objects, then there is no guarantee for thread1 to run postPhoto and then immediately after that getData even if you call sequentially. Another thread may take the turn and start running in between thread1 calling those 2 methods.
Bear in mind, synchronized keyword locks on the class itself so at any time there will be only one method executing. No 2 synchronized methods will be run at the same time.
Yes, you are right. The combination of synchronized and static guarantees what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With