V
- public abstract class Service<V> extends Object implements Worker<V>, EventTarget
A Service is a non-visual component encapsulating the information required to perform some work on one or more background threads. As part of the JavaFX UI library, the Service knows about the JavaFX Application thread and is designed to relieve the application developer from the burden of managing multithreaded code that interacts with the user interface. As such, all of the methods and state on the Service are intended to be invoked exclusively from the JavaFX Application thread. The only exception to this, is when initially configuring a Service, which may safely be done from any thread, and initially starting a Service, which may also safely be done from any thread. However, once the Service has been initialized and started, it may only thereafter be used from the FX thread.
A Service creates and manages a Task
that performs the work
on the background thread.
Service implements Worker
. As such, you can observe the state of
the background task and optionally cancel it. Service is a reusable
Worker, meaning that it can be reset and restarted. Due to this, a Service
can be constructed declaratively and restarted on demand.
Once a Service is started, it will schedule its Task and listen for
changes to the state of the Task. A Task does not hold a reference to the
Service that started it, meaning that a running Task will not prevent
the Service from being garbage collected.
If an Executor
is specified on the Service,
then it will be used to actually execute the service. Otherwise,
a daemon thread will be created and executed. If you wish to create
non-daemon threads, then specify a custom Executor (for example,
you could use a ThreadPoolExecutor
with a custom
ThreadFactory
).
Because a Service is intended to simplify declarative use cases, subclasses
should expose as properties the input parameters to the work to be done.
For example, suppose I wanted to write a Service which read the first line
from any URL and returned it as a String. Such a Service might be defined,
such that it had a single property, url
. It might be implemented
as:
public static class FirstLineService extends Service<String> {
private StringProperty url = new SimpleStringProperty(this, "url");
public final void setUrl(String value) { url.set(value); }
public final String getUrl() { return url.get(); }
public final StringProperty urlProperty() { return url; }
protected Task createTask() {
final String _url = getUrl();
return new Task<String>() {
protected String call() throws Exception {
URL u = new URL(_url);
BufferedReader in = new BufferedReader(
new InputStreamReader(u.openStream()));
String result = in.readLine();
in.close();
return result;
}
};
}
}
The Service by default uses a thread pool Executor with some unspecified default or maximum thread pool size. This is done so that naive code will not completely swamp the system by creating thousands of Threads.
Worker.State
Modifier | Constructor and Description |
---|---|
protected |
Service()
Create a new Service.
|
Modifier and Type | Method and Description |
---|---|
<T extends Event> |
addEventFilter(EventType<T> eventType,
EventHandler<? super T> eventFilter)
Registers an event filter to this task.
|
<T extends Event> |
addEventHandler(EventType<T> eventType,
EventHandler<? super T> eventHandler)
Registers an event handler to this task.
|
EventDispatchChain |
buildEventDispatchChain(EventDispatchChain tail)
Construct an event dispatch chain for this target.
|
boolean |
cancel()
Cancels any currently running Task, if any.
|
protected void |
cancelled()
A protected convenience method for subclasses, called whenever the
state of the Service has transitioned to the CANCELLED state.
|
protected abstract Task<V> |
createTask()
Invoked after the Service is started on the JavaFX Application Thread.
|
ReadOnlyObjectProperty<Throwable> |
exceptionProperty()
Gets the ReadOnlyObjectProperty representing any exception which occurred.
|
protected void |
executeTask(Task<V> task)
Uses the
executor defined on this Service to execute the
given task. |
ObjectProperty<Executor> |
executorProperty() |
protected void |
failed()
A protected convenience method for subclasses, called whenever the
state of the Service has transitioned to the FAILED state.
|
protected void |
fireEvent(Event event)
Fires the specified event.
|
Throwable |
getException()
Indicates the exception which occurred while the Worker was running, if any.
|
Executor |
getExecutor() |
String |
getMessage()
Gets a message associated with the current state of this Worker.
|
EventHandler<WorkerStateEvent> |
getOnCancelled()
The onCancelled event handler is called whenever the Task state
transitions to the CANCELLED state.
|
EventHandler<WorkerStateEvent> |
getOnFailed()
The onFailed event handler is called whenever the Task state
transitions to the FAILED state.
|
EventHandler<WorkerStateEvent> |
getOnReady()
The onReady event handler is called whenever the Task state transitions
to the READY state.
|
EventHandler<WorkerStateEvent> |
getOnRunning()
The onRunning event handler is called whenever the Task state
transitions to the RUNNING state.
|
EventHandler<WorkerStateEvent> |
getOnScheduled()
The onSchedule event handler is called whenever the Task state
transitions to the SCHEDULED state.
|
EventHandler<WorkerStateEvent> |
getOnSucceeded()
The onSucceeded event handler is called whenever the Task state
transitions to the SUCCEEDED state.
|
double |
getProgress()
Indicates the current progress of this Worker in terms of percent complete.
|
Worker.State |
getState()
Specifies the current state of this Worker.
|
String |
getTitle()
An optional title that should be associated with this Worker.
|
double |
getTotalWork()
Indicates a maximum value for the
Worker.workDoneProperty() property. |
V |
getValue()
Specifies the value, or result, of this Worker.
|
double |
getWorkDone()
Indicates the current amount of work that has been completed.
|
boolean |
isRunning()
True if the state is either SCHEDULED or RUNNING.
|
ReadOnlyStringProperty |
messageProperty()
Gets the ReadOnlyStringProperty representing the message.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onCancelledProperty()
The onCancelled event handler is called whenever the Task state
transitions to the CANCELLED state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onFailedProperty()
The onFailed event handler is called whenever the Task state
transitions to the FAILED state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onReadyProperty()
The onReady event handler is called whenever the Task state transitions
to the READY state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onRunningProperty()
The onRunning event handler is called whenever the Task state
transitions to the RUNNING state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onScheduledProperty()
The onSchedule event handler is called whenever the Task state
transitions to the SCHEDULED state.
|
ObjectProperty<EventHandler<WorkerStateEvent>> |
onSucceededProperty()
The onSucceeded event handler is called whenever the Task state
transitions to the SUCCEEDED state.
|
ReadOnlyDoubleProperty |
progressProperty()
Gets the ReadOnlyDoubleProperty representing the progress.
|
protected void |
ready()
A protected convenience method for subclasses, called whenever the
state of the Service has transitioned to the READY state.
|
<T extends Event> |
removeEventFilter(EventType<T> eventType,
EventHandler<? super T> eventFilter)
Unregisters a previously registered event filter from this task.
|
<T extends Event> |
removeEventHandler(EventType<T> eventType,
EventHandler<? super T> eventHandler)
Unregisters a previously registered event handler from this task.
|
void |
reset()
Resets the Service.
|
void |
restart()
Cancels any currently running Task, if any, and restarts this Service.
|
protected void |
running()
A protected convenience method for subclasses, called whenever the
state of the Service has transitioned to the RUNNING state.
|
ReadOnlyBooleanProperty |
runningProperty()
Gets the ReadOnlyBooleanProperty representing whether the Worker is running.
|
protected void |
scheduled()
A protected convenience method for subclasses, called whenever the
state of the Service has transitioned to the SCHEDULED state.
|
protected <T extends Event> |
setEventHandler(EventType<T> eventType,
EventHandler<? super T> eventHandler)
Sets the handler to use for this event type.
|
void |
setExecutor(Executor value) |
void |
setOnCancelled(EventHandler<WorkerStateEvent> value)
The onCancelled event handler is called whenever the Task state
transitions to the CANCELLED state.
|
void |
setOnFailed(EventHandler<WorkerStateEvent> value)
The onFailed event handler is called whenever the Task state
transitions to the FAILED state.
|
void |
setOnReady(EventHandler<WorkerStateEvent> value)
The onReady event handler is called whenever the Task state transitions
to the READY state.
|
void |
setOnRunning(EventHandler<WorkerStateEvent> value)
The onRunning event handler is called whenever the Task state
transitions to the RUNNING state.
|
void |
setOnScheduled(EventHandler<WorkerStateEvent> value)
The onSchedule event handler is called whenever the Task state
transitions to the SCHEDULED state.
|
void |
setOnSucceeded(EventHandler<WorkerStateEvent> value)
The onSucceeded event handler is called whenever the Task state
transitions to the SUCCEEDED state.
|
void |
start()
Starts this Service.
|
ReadOnlyObjectProperty<Worker.State> |
stateProperty()
Gets the ReadOnlyObjectProperty representing the current state.
|
protected void |
succeeded()
A protected convenience method for subclasses, called whenever the
state of the Service has transitioned to the SUCCEEDED state.
|
ReadOnlyStringProperty |
titleProperty()
Gets the ReadOnlyStringProperty representing the title.
|
ReadOnlyDoubleProperty |
totalWorkProperty()
Gets the ReadOnlyDoubleProperty representing the maximum amount of work
that needs to be done.
|
ReadOnlyObjectProperty<V> |
valueProperty()
Gets the ReadOnlyObjectProperty representing the value.
|
ReadOnlyDoubleProperty |
workDoneProperty()
Gets the ReadOnlyDoubleProperty representing the current progress.
|
public final Worker.State getState()
Worker
public final ReadOnlyObjectProperty<Worker.State> stateProperty()
Worker
stateProperty
in interface Worker<V>
public final V getValue()
Worker
public final ReadOnlyObjectProperty<V> valueProperty()
Worker
valueProperty
in interface Worker<V>
public final Throwable getException()
Worker
null
, there is no known exception, even if
the status is FAILED. If this property is not null
, it will most
likely contain an exception that describes the cause of failure.getException
in interface Worker<V>
public final ReadOnlyObjectProperty<Throwable> exceptionProperty()
Worker
exceptionProperty
in interface Worker<V>
public final double getWorkDone()
Worker
getWorkDone
in interface Worker<V>
Worker.totalWorkProperty()
,
Worker.progressProperty()
public final ReadOnlyDoubleProperty workDoneProperty()
Worker
workDoneProperty
in interface Worker<V>
public final double getTotalWork()
Worker
Worker.workDoneProperty()
property. The
totalWork will either be -1 (indicating that the amount of work
to do is indeterminate), or it will be a non-zero value less than or
equal to Double.MAX_VALUE.getTotalWork
in interface Worker<V>
Worker.workDoneProperty()
,
Worker.progressProperty()
public final ReadOnlyDoubleProperty totalWorkProperty()
Worker
totalWorkProperty
in interface Worker<V>
public final double getProgress()
Worker
getProgress
in interface Worker<V>
Worker.workDoneProperty()
,
Worker.totalWorkProperty()
public final ReadOnlyDoubleProperty progressProperty()
Worker
progressProperty
in interface Worker<V>
public final boolean isRunning()
Worker
ProgressIndicator
, you will typically bind the visibility
of the ProgressIndicator to the Worker's running property, and the progress of the
ProgressIndicator to the Worker's progress property.public final ReadOnlyBooleanProperty runningProperty()
Worker
runningProperty
in interface Worker<V>
public final String getMessage()
Worker
getMessage
in interface Worker<V>
public final ReadOnlyStringProperty messageProperty()
Worker
messageProperty
in interface Worker<V>
public final String getTitle()
Worker
public final ReadOnlyStringProperty titleProperty()
Worker
titleProperty
in interface Worker<V>
public final void setExecutor(Executor value)
public final Executor getExecutor()
public final ObjectProperty<Executor> executorProperty()
public final ObjectProperty<EventHandler<WorkerStateEvent>> onReadyProperty()
public final EventHandler<WorkerStateEvent> getOnReady()
public final void setOnReady(EventHandler<WorkerStateEvent> value)
value
- the event handler, can be null to clear itprotected void ready()
public final ObjectProperty<EventHandler<WorkerStateEvent>> onScheduledProperty()
public final EventHandler<WorkerStateEvent> getOnScheduled()
public final void setOnScheduled(EventHandler<WorkerStateEvent> value)
value
- the event handler, can be null to clear itprotected void scheduled()
public final ObjectProperty<EventHandler<WorkerStateEvent>> onRunningProperty()
public final EventHandler<WorkerStateEvent> getOnRunning()
public final void setOnRunning(EventHandler<WorkerStateEvent> value)
value
- the event handler, can be null to clear itprotected void running()
public final ObjectProperty<EventHandler<WorkerStateEvent>> onSucceededProperty()
public final EventHandler<WorkerStateEvent> getOnSucceeded()
public final void setOnSucceeded(EventHandler<WorkerStateEvent> value)
value
- the event handler, can be null to clear itprotected void succeeded()
public final ObjectProperty<EventHandler<WorkerStateEvent>> onCancelledProperty()
public final EventHandler<WorkerStateEvent> getOnCancelled()
public final void setOnCancelled(EventHandler<WorkerStateEvent> value)
value
- the event handler, can be null to clear itprotected void cancelled()
public final ObjectProperty<EventHandler<WorkerStateEvent>> onFailedProperty()
public final EventHandler<WorkerStateEvent> getOnFailed()
public final void setOnFailed(EventHandler<WorkerStateEvent> value)
value
- the event handler, can be null to clear itprotected void failed()
public boolean cancel()
public void restart()
public void reset()
public void start()
protected void executeTask(Task<V> task)
Uses the executor
defined on this Service to execute the
given task. If the executor
is null, then a default
executor is used which will create a new daemon thread on which to
execute this task.
This method is intended only to be called by the Service implementation.
task
- a non-null task to executepublic final <T extends Event> void addEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)
T
- the specific event class of the handlereventType
- the type of the events to receive by the handlereventHandler
- the handler to registerNullPointerException
- if the event type or handler is nullpublic final <T extends Event> void removeEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)
T
- the specific event class of the handlereventType
- the event type from which to unregistereventHandler
- the handler to unregisterNullPointerException
- if the event type or handler is nullpublic final <T extends Event> void addEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter)
T
- the specific event class of the filtereventType
- the type of the events to receive by the filtereventFilter
- the filter to registerNullPointerException
- if the event type or filter is nullpublic final <T extends Event> void removeEventFilter(EventType<T> eventType, EventHandler<? super T> eventFilter)
T
- the specific event class of the filtereventType
- the event type from which to unregistereventFilter
- the filter to unregisterNullPointerException
- if the event type or filter is nullprotected final <T extends Event> void setEventHandler(EventType<T> eventType, EventHandler<? super T> eventHandler)
T
- the specific event class of the handlereventType
- the event type to associate with the given eventHandlereventHandler
- the handler to register, or null to unregisterNullPointerException
- if the event type is nullprotected final void fireEvent(Event event)
This method must be called on the FX user thread.
event
- the event to firepublic EventDispatchChain buildEventDispatchChain(EventDispatchChain tail)
EventTarget
EventTarget
. This event target is
not automatically added to the chain, so if it wants to process events,
it needs to add an EventDispatcher
for itself to the chain.
In the case the event target is part of some hierarchy, the chain for it is usually built from event dispatchers collected from the root of the hierarchy to the event target.
The event dispatch chain is constructed by modifications to the provided initial event dispatch chain. The returned chain should have the initial chain at its end so the dispatchers should be prepended to the initial chain.
The caller shouldn't assume that the initial chain remains unchanged nor that the returned value will reference a different chain.
buildEventDispatchChain
in interface EventTarget
tail
- the initial chain to build fromprotected abstract Task<V> createTask()
protected Task createTask() {
final String url = myService.getUrl();
return new Task<String>() {
protected String call() {
URL u = new URL("http://www.oracle.com");
BufferedReader in = new BufferedReader(
new InputStreamReader(u.openStream()));
String result = in.readLine();
in.close();
return result;
}
}
}
If the Task is a pre-defined class (as opposed to being an anonymous class), and if it followed the recommended best-practice, then there is no need to save off state prior to constructing the Task since its state is completely provided in its constructor.
protected Task createTask() {
// This is safe because getUrl is called on the FX Application
// Thread and the FirstLineReaderTasks stores it as an
// immutable property
return new FirstLineReaderTask(myService.getUrl());
}
Copyright © 2020. All rights reserved.