Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to call method in new thread

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).

like image 763
Sk1X1 Avatar asked Apr 07 '13 19:04

Sk1X1


1 Answers

Since Java 8 you can use shorter form:

new Thread(() -> {
    // Insert some method call here.
}).start();

Update: Also, you could use method reference:

class Example {

    public static void main(String[] args){
        new Thread(Example::someMethod).start();
    }

    public static void someMethod(){
        // Insert some code here
    }

}

You are able to use it when your argument list is the same as in required @FunctionalInterface, e.g. Runnable or Callable.

Update 2: I strongly recommend utilizing java.util.concurrent.Executors#newSingleThreadExecutor() for executing fire-and-forget tasks.

Example:

Executors
    .newSingleThreadExecutor()
    .submit(Example::someMethod);

See more: Platform.runLater and Task in JavaFX, Method References.

like image 105
Andrii Abramov Avatar answered Oct 11 '22 07:10

Andrii Abramov