Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to communicate user defined objects and exceptions between Service and UI in JavaFX2?

How to communicate user defined objects and user defined (checked) exceptions between Service and UI in JavaFX2? The examples only show String being sent in to the Service as a property and array of observable Strings being sent back to the UI.

Properties seem to be defined only for simple types. StringProperty, IntegerProperty, DoubleProperty etc. Currently I have a user defined object (not a simple type), that I want Task to operate upon and update with the output data it produced. I am sending it through the constructor of Service which passes it on through the constructor of Task. I wondered about the stricture that parameters must be passed in via properties. Also if an exception is thrown during Task's operation, How would it be passed from Service to the UI? I see only a getException() method, no traditional throw/catch.

Properties http://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm

Service and Task http://docs.oracle.com/javafx/2/threads/jfxpub-threads.htm

Service javadocs http://docs.oracle.com/javafx/2/api/javafx/concurrent/Service.html#getException()

"Because the Task is designed for use with JavaFX GUI applications, it ensures that every change to its public properties, as well as change notifications for state, errors, and for event handlers, all occur on the main JavaFX application thread. Accessing these properties from a background thread (including the call() method) will result in runtime exceptions being raised.

It is strongly encouraged that all Tasks be initialized with immutable state upon which the Task will operate. This should be done by providing a Task constructor which takes the parameters necessary for execution of the Task. Immutable state makes it easy and safe to use from any thread and ensures correctness in the presence of multiple threads."

But if my UI only touches the object after Task is done, then it should be ok, right?

like image 742
likejudo Avatar asked Feb 18 '23 23:02

likejudo


1 Answers

Service has a signature Service<V> the <V> is a generic type parameter used to specify the type of the return object from the service's supplied task.

Let's say you want to define a service which returns a user defined object of type Foo, then you can do it like this:

 class FooGenerator extends Service<Foo> {
   protected Task createTask() {
     return new Task<Foo>() {
       protected Foo call() throws Exception {
         return new Foo();
       }
     };
   }
 }

To use the service:

 FooGenerator fooGenerator = new FooGenerator();
 fooGenerator.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
   @Override public void handle(WorkerStateEvent t) {
     Foo myNewFoo = fooGenerator.getValue();
     System.out.println(myNewFoo);
   }
 });
 fooGenerator.start();

If you want to pass an input value into the service each time before you start or restart it, you have to be a little bit more careful. You can add the values you want to input to the service as settable members on the service. These setters can be called from the JavaFX application thread, before the service's start method is invoked. Then, when the service's task is created, pass the parameters through to the service's Task's constructor.

When doing this it is best to make all information passable back and forth between threads immutable. For the example below, a Foo object is passed as an input parameter to the service and a Foo object based on the input received as an output of the service. But the state of Foo itself is only initialized in it's constructor - the instances of Foo are immutable and cannot be changed once created and all of it's member variables are final and cannot change. This makes it much easier to reason about the program, as you never need worry that another thread might overwrite the state concurrently. It seems a little bit complicated, but it does make everything very safe.

class FooModifier extends Service<Foo> {
  private Foo foo;
  void setFoo(Foo foo) { this.foo = foo; }

  @Override protected Task createTask() {
    return new FooModifierTask(foo);
  }

  private class FooModifierTask extends Task<Foo> {
    final private Foo fooInput;
    FooModifierTask(Foo fooInput) { this.fooInput = fooInput; }

    @Override protected Foo call() throws Exception {
      Thread.currentThread().sleep(1000);
      return new Foo(fooInput);
    }
  }
}

class Foo {
  private final int answer;
  Foo()          { answer = random.nextInt(100); }
  Foo(Foo input) { answer = input.getAnswer() + 42; }
  public int getAnswer() { return answer; }
}

There is a further example of providing input to a Service in the Service javadoc.


To return a custom user exception from the service, just throw the user exception during the service's task call handler. For example:

 class BadFooGenerator extends Service<Foo> {
   @Override protected Task createTask() {
     return new Task<Foo>() {
       @Override protected Foo call() throws Exception {
         Thread.currentThread().sleep(1000);
         throw new BadFooException();
       }
     };
   }
 }

And the exception can be retrieved like this:

 BadFooGenerator badFooGenerator = new BadFooGenerator();
 badFooGenerator.setOnFailed(new EventHandler<WorkerStateEvent>() {
   @Override public void handle(WorkerStateEvent t) {
     Throwable ouch = badFooGenerator.getException();
     System.out.println(ouch.getClass().getName() + " -> " + ouch.getMessage());
   }
 });
 badFooGenerator.start();

I created a couple of executable samples you can use to try this out.

like image 197
jewelsea Avatar answered Mar 10 '23 09:03

jewelsea