I am using a data-related API interface which has a key void callback function that is automatically invoked to mark the end of some IO operations. I want to make the class Callable<String>
and use Future<String> result
.
I struggle to figure how to make the Callable return a String. Making a String returnResult(){return this.result}
function to call inside doesn’t do.
Please advise.
It looks something like:
<code>public class MyCallable implements someAPIWrapper, Callable<String> {
String result;
@Override
public void endOfJobCallback() { //predefined API callback marking end of work
/*
usually read the data and write to a file, but not my case.
how to return this.result string from here?
*/
}
@Override
public String call() throws Exception {
//some logic stuff
//make API call to request a bunch of data
//receiving messages and appending to the *result* variable
//end of all messages, so the ending callback is automatically entered
}
}
class Main {
public static void main(String[] args){
MyCallable callable = new MyCallable();
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(callable);
String result = future.get(); //blocking until result ready
}
}
</code>
<code>public class MyCallable implements someAPIWrapper, Callable<String> {
String result;
@Override
public void endOfJobCallback() { //predefined API callback marking end of work
/*
usually read the data and write to a file, but not my case.
how to return this.result string from here?
*/
}
@Override
public String call() throws Exception {
//some logic stuff
//make API call to request a bunch of data
//receiving messages and appending to the *result* variable
//end of all messages, so the ending callback is automatically entered
}
}
class Main {
public static void main(String[] args){
MyCallable callable = new MyCallable();
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(callable);
String result = future.get(); //blocking until result ready
}
}
</code>
public class MyCallable implements someAPIWrapper, Callable<String> {
String result;
@Override
public void endOfJobCallback() { //predefined API callback marking end of work
/*
usually read the data and write to a file, but not my case.
how to return this.result string from here?
*/
}
@Override
public String call() throws Exception {
//some logic stuff
//make API call to request a bunch of data
//receiving messages and appending to the *result* variable
//end of all messages, so the ending callback is automatically entered
}
}
class Main {
public static void main(String[] args){
MyCallable callable = new MyCallable();
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(callable);
String result = future.get(); //blocking until result ready
}
}