How should I set my future result from Runnable?
Sorry if the solution is trivial, or if the question has already been asked, I am starting with Java and I could not find an answer to this problem.
Basically I'm looking for a future / promise mechanism like C ++ 11 suggestions. Java on Android doesn't seem to offer this. I am returning a future where the value can be set later by a listener.
Here is the code I am struggling with:
class SettableFutureTask extends FutureTask<Boolean> {
public void setValue (boolean value) {
set (new Boolean (value));
}
}
Future<Boolean> future = new SettableFutureTask (new Runnable () {
public void run () {
...
mManager.setListener (new Listener (SettableFutureTask.this));
}
});
return future;
The aim is for the listener to establish the meaning of the future, hence SettableFutureTask
that the public offers setValue()
.
My problem with this code is accessing the instance SettableFutureTask
from the method run()
in Runnable
. I have also tried to rewrite some Runnable and FutureTask classes to achieve this but to no avail.
How can I solve this problem? Thank,
source to share
If you want to access the instance from run (), you can try declaring the future as final, so it's accessible from the scope of the method:
final Future<Boolean> future = new SettableFutureTask (new Runnable () {
public void run () {
...
mManager.setListener (new Listener (future));
}
});
source to share