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);
}
}
}