I'm writing small app and now I discovered a problem. I need to call one(later maybe two) method (this method loads something and returns the result) without lagging in window of app.
I found classes like Executor
or Callable
, but I don't understand how to work with those ones.
Can you please post any solution, which helps me?
Thanks for all advices.
Edit: The method MUST return the result. This result depends on parametrs. Something like this:
public static HtmlPage getPage(String page) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
return webClient.getPage(page);
}
This method works about 8-10 seconds. After execute this method, thread can be stopped. But I need to call the methods every 2 minutes.
Edit: I edited code with this:
public static HtmlPage getPage(final String page) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
Thread thread = new Thread() {
public void run() {
try {
loadedPage = webClient.getPage(page);
} catch (FailingHttpStatusCodeException | IOException e) {
e.printStackTrace();
}
}
};
thread.start();
try {
return loadedPage;
} catch (Exception e) {
return null;
}
}
With this code I get error again (even if I put return null
out of catch block).
Executor
andExecutorService
have examples in the javadoc. And a topic on the concurrency thread in the official tutorial. That's where I start. You should ask a new question if you don't understand something specific in those materials, or if you're stuck having used the information in them. – SchmuckExecutorService.submit()
with aCallable<HtmlPage>
, so focus on the documentation for those and related classes/methods.submit()
should return aFuture<HtmlPage>
which will let you do something (like update the UI) when the result is available. – Schmuck