Home Async return with delay - IllegalMonitorStateException
Reply: 0

Async return with delay - IllegalMonitorStateException

user2034
1#
user2034 Published in April 26, 2018, 1:45 pm

I am trying to call method in new thread which will return something after delay using callable. It is falling due to IllegalMonitorStateException Is it possible to encapsulate thread service that way, when I will just create instance of class, call method and that method will return object with delay? Thank you in advance.

// ENTITY
public class Result {
    public String name;
    public int value;

    public Result(String name, int value) {
        this.name = name;
        this.value = value;
    }

    public Result() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Result{" +
                "name='" + name + '\'' +
                ", value=" + value +
                '}';
    }
}

Creation of thread with delay and return value

import java.util.concurrent.*;

public class AsyncCallable {

    public Result calculate() throws ExecutionException, InterruptedException {

        int delay = 5000;
        ExecutorService executorService = Executors.newSingleThreadExecutor();

        Callable<Result> callable = () -> {
            this.wait(delay);
            return new Result("Name", 4);
        };

        Future<Result> future = executorService.submit(callable);
        executorService.shutdown();
        return future.get();
    }

}

Calling method:

import java.util.concurrent.ExecutionException;

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        AsyncCallable asyncCallable = new AsyncCallable();

        System.out.println(asyncCallable.calculate().toString());


    }
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.490306 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO