1
\$\begingroup\$

I wanted to make a class that connects to my server and returns a value, a URL in this case. As Android 4.0 doesn't let me run network task on the main UI thread (rightly so) I have made this.

Please give me your feedback as to if it is thread safe or not and ways to improve it. I have never used ExecutorService or Future before so I would be grateful to know if I am using it correctly. I would also like to know if this is blocking the thread that called getDownloadURL.

public class DownloadURLServerGetter implements DownloadURLGetter {
 private ServerAdapter serverAdapter;
 private String id;
 @Inject
 public DownloadURLServerGetter(ServerAdapter serverAdapter) {
 this.serverAdapter = serverAdapter;
 }
 @Override
 public synchronized String getDownloadURL(String id) throws IOException {
 this.id = id;
 final ExecutorService service;
 final Future<String> task;
 service = Executors.newFixedThreadPool(1);
 task = service.submit(new MyCallable());
 try {
 return task.get();
 } catch (InterruptedException e) {
 throw new IOException(e);
 } catch (ExecutionException e) {
 throw new IOException(e);
 }
 }
 public class MyCallable implements Callable<String> {
 @Override
 public String call() throws Exception {
 HttpResponse resp = serverAdapter.get("blobs/" + id);
 String url = EntityUtils.toString(resp.getEntity());
 return Parser.parseURL(url);
 }
 }
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 15, 2012 at 9:40
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

Your method seems thread safe, but you are blocking getDownloadURL() because task.get() will only return once the underlying job finishes. Try reading up on Java's future and see how you can use them more efficient and correct.

Your executor service should most likely only be created once for your application.

By the way: if you pass ServerAdapter and id to MyCallable (as constructor arguments) you no longer need to keep getDownloadURL synchronized or MyCallable non-static.

Mast
13.8k12 gold badges57 silver badges127 bronze badges
answered Jun 15, 2012 at 11:01
\$\endgroup\$
1
  • \$\begingroup\$ thank you for that. I realised I was blocking the calling thread. I have actually modified the thread that was calling this method so it seems to work pretty well at the moment tho as you pointed out there is room for improvement. \$\endgroup\$ Commented Jun 15, 2012 at 11:07

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.