What is the best way to get return value from asyncExec in Eclipse?

I write Eclipse plugins and often have a situation where the current task needs to pause a bit, start asynchronously in the user interface thread, and resume.

So my code usually looks something like this:

Display display = Display.getDefault();
display.syncExec(new Runnable() {
    public void run() {
                // Do some calculation
                // How do I return a value from here?
    }
});
// I want to be able to use the calculation result here!

One way to do this is to have the entire Job class have some kind of field. Another is to use a custom class (rather than anonymous for this and use its resulting data field, etc.). What is the best and most elegant approach?

+5
source share
3 answers

, , async Runnable asyncExec.

, / (, ) , , - java.util.concurrent.Future.

+4

, - "" . . - . , , Runnable, , , . , , :

final Object[] result = new Object[1];
Display display = Display.getDefault();
display.syncExec(new Runnable()
{
  public void run()
  {
    result[0] = "foo";
  }
}
System.out.println(result[0]);

, "" , , , , .

UPDATE , , , , . , , Runnable , , syncExec. - AtomicReference:

final AtomicReference<Object> result = new AtomicReference<Object>();
Display display = Display.getDefault();
display.syncExec(new Runnable()
{
  public void run()
  {
    result.set("foo");
  }
}
System.out.println(result.get());

AtomicReference , . .

+7

, , - run().

:

final Container container = new Container();
Display display = Display.getDefault();
display.syncExec(new Runnable()
{
  public void run()
  {
    container.setValue("foo");
  }
}
System.out.println(container.getValue());

:

public class Container {
  private Object value;
  public Object getValue() {
    return value;
  }
  public void setValue(Object o) {
    value = o;
  }
}

, , ( , 1- ), syncExec , .

, - asyncExec()..

0
source

All Articles