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