V
- the type of object returned by the Servicepublic abstract class Service<V> extends java.lang.Object implements Worker<V>
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.
Type | Property and Description |
---|---|
<any> |
exception
Gets the ReadOnlyObjectProperty representing any exception which occurred.
|
<any> |
executor
The executor to use for running this Service.
|
ReadOnlyStringProperty |
message
Gets the ReadOnlyStringProperty representing the message.
|
<any> |
onCancelled
The onCancelled event handler is called whenever the Task state
transitions to the CANCELLED state.
|
<any> |
onFailed
The onFailed event handler is called whenever the Task state
transitions to the FAILED state.
|
<any> |
onReady
The onReady event handler is called whenever the Task state transitions
to the READY state.
|
<any> |
onRunning
The onRunning event handler is called whenever the Task state
transitions to the RUNNING state.
|
<any> |
onScheduled
The onSchedule event handler is called whenever the Task state
transitions to the SCHEDULED state.
|
<any> |
onSucceeded
The onSucceeded event handler is called whenever the Task state
transitions to the SUCCEEDED state.
|
ReadOnlyDoubleProperty |
progress
Gets the ReadOnlyDoubleProperty representing the progress.
|
ReadOnlyBooleanProperty |
running
Gets the ReadOnlyBooleanProperty representing whether the Worker is running.
|
<any> |
state
Gets the ReadOnlyObjectProperty representing the current state.
|
ReadOnlyStringProperty |
title
Gets the ReadOnlyStringProperty representing the title.
|
ReadOnlyDoubleProperty |
totalWork
Gets the ReadOnlyDoubleProperty representing the maximum amount of work
that needs to be done.
|
<any> |
value
Gets the ReadOnlyObjectProperty representing the value.
|
ReadOnlyDoubleProperty |
workDone
Gets the ReadOnlyDoubleProperty representing the current progress.
|
Worker.State
Modifier and Type | Field and Description |
---|---|
private EventHelper |
eventHelper
*
Event Dispatch *
*
|
private <any> |
exception |
private <any> |
executor
The executor to use for running this Service.
|
private static java.util.concurrent.ThreadPoolExecutor |
EXECUTOR |
private static java.util.concurrent.BlockingQueue<java.lang.Runnable> |
IO_QUEUE
Because the ThreadPoolExecutor works completely backwards from what we want (ie:
it doesn't increase thread count beyond the core pool size unless the queue is full),
our queue has to be smart in that it will REJECT an item in the queue unless the
thread size in the EXECUTOR is > 32, in which case we will queue up.
|
private static PlatformLogger |
LOG
Logger used in the case of some uncaught exceptions
|
private StringProperty |
message |
private DoubleProperty |
progress |
private BooleanProperty |
running |
private boolean |
startedOnce
This boolean is set to true once the Service has been initially started.
|
private <any> |
state |
private Task<V> |
task
A reference to the last task that was executed.
|
private static java.util.concurrent.ThreadFactory |
THREAD_FACTORY |
private static java.lang.ThreadGroup |
THREAD_GROUP |
private static int |
THREAD_POOL_SIZE |
private static long |
THREAD_TIME_OUT |
private StringProperty |
title |
private DoubleProperty |
totalWorkToBeDone |
private static java.lang.Thread.UncaughtExceptionHandler |
UNCAUGHT_HANDLER |
private <any> |
value |
private DoubleProperty |
workDone |
Modifier | Constructor and Description |
---|---|
protected |
Service()
Create a new Service.
|
Modifier and Type | Method and Description |
---|---|
<T extends Event> |
addEventFilter(<any> eventType,
<any> eventFilter)
Registers an event filter to this task.
|
<T extends Event> |
addEventHandler(<any> eventType,
<any> eventHandler)
Registers an event handler to this task.
|
EventDispatchChain |
buildEventDispatchChain(EventDispatchChain tail) |
boolean |
cancel()
Cancels any currently running Task, if any.
|
(package private) void |
cancelFromReadyState()
This is used by ScheduledService to cancel a Service that is in the READY state.
|
protected void |
cancelled()
A protected convenience method for subclasses, called whenever the
state of the Service has transitioned to the CANCELLED state.
|
(package private) void |
checkThread() |
protected abstract Task<V> |
createTask()
Invoked after the Service is started on the JavaFX Application Thread.
|
<any> |
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. |
<any> |
executorProperty()
The executor to use for running this Service.
|
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.
|
private EventHelper |
getEventHelper() |
java.lang.Throwable |
getException()
Gets the value of the property exception.
|
java.util.concurrent.Executor |
getExecutor()
Gets the value of the property executor.
|
java.lang.String |
getMessage()
Gets the value of the property message.
|
<any> |
getOnCancelled()
The onCancelled event handler is called whenever the Task state
transitions to the CANCELLED state.
|
<any> |
getOnFailed()
The onFailed event handler is called whenever the Task state
transitions to the FAILED state.
|
<any> |
getOnReady()
The onReady event handler is called whenever the Task state transitions
to the READY state.
|
<any> |
getOnRunning()
The onRunning event handler is called whenever the Task state
transitions to the RUNNING state.
|
<any> |
getOnScheduled()
The onSchedule event handler is called whenever the Task state
transitions to the SCHEDULED state.
|
<any> |
getOnSucceeded()
The onSucceeded event handler is called whenever the Task state
transitions to the SUCCEEDED state.
|
double |
getProgress()
Gets the value of the property progress.
|
Worker.State |
getState()
Gets the value of the property state.
|
java.lang.String |
getTitle()
Gets the value of the property title.
|
double |
getTotalWork()
Gets the value of the property totalWork.
|
V |
getValue()
Gets the value of the property value.
|
double |
getWorkDone()
Gets the value of the property workDone.
|
(package private) boolean |
isFxApplicationThread() |
boolean |
isRunning()
Gets the value of the property running.
|
ReadOnlyStringProperty |
messageProperty()
Gets the ReadOnlyStringProperty representing the message.
|
<any> |
onCancelledProperty()
The onCancelled event handler is called whenever the Task state
transitions to the CANCELLED state.
|
<any> |
onFailedProperty()
The onFailed event handler is called whenever the Task state
transitions to the FAILED state.
|
<any> |
onReadyProperty()
The onReady event handler is called whenever the Task state transitions
to the READY state.
|
<any> |
onRunningProperty()
The onRunning event handler is called whenever the Task state
transitions to the RUNNING state.
|
<any> |
onScheduledProperty()
The onSchedule event handler is called whenever the Task state
transitions to the SCHEDULED state.
|
<any> |
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(<any> eventType,
<any> eventFilter)
Unregisters a previously registered event filter from this task.
|
<T extends Event> |
removeEventHandler(<any> eventType,
<any> 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.
|
(package private) void |
runLater(java.lang.Runnable r) |
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(<any> eventType,
<any> eventHandler)
Sets the handler to use for this event type.
|
void |
setExecutor(java.util.concurrent.Executor value)
Sets the value of the property executor.
|
void |
setOnCancelled(<any> value)
The onCancelled event handler is called whenever the Task state
transitions to the CANCELLED state.
|
void |
setOnFailed(<any> value)
The onFailed event handler is called whenever the Task state
transitions to the FAILED state.
|
void |
setOnReady(<any> value)
The onReady event handler is called whenever the Task state transitions
to the READY state.
|
void |
setOnRunning(<any> value)
The onRunning event handler is called whenever the Task state
transitions to the RUNNING state.
|
void |
setOnScheduled(<any> value)
The onSchedule event handler is called whenever the Task state
transitions to the SCHEDULED state.
|
void |
setOnSucceeded(<any> value)
The onSucceeded event handler is called whenever the Task state
transitions to the SUCCEEDED state.
|
void |
start()
Starts this Service.
|
<any> |
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.
|
<any> |
valueProperty()
Gets the ReadOnlyObjectProperty representing the value.
|
ReadOnlyDoubleProperty |
workDoneProperty()
Gets the ReadOnlyDoubleProperty representing the current progress.
|
public final <any> stateProperty
stateProperty
in interface Worker<V>
getState()
public final <any> valueProperty
valueProperty
in interface Worker<V>
getValue()
public final <any> exceptionProperty
exceptionProperty
in interface Worker<V>
getException()
public final ReadOnlyDoubleProperty workDoneProperty
workDoneProperty
in interface Worker<V>
getWorkDone()
public final ReadOnlyDoubleProperty totalWorkProperty
totalWorkProperty
in interface Worker<V>
getTotalWork()
public final ReadOnlyDoubleProperty progressProperty
progressProperty
in interface Worker<V>
getProgress()
public final ReadOnlyBooleanProperty runningProperty
runningProperty
in interface Worker<V>
isRunning()
public final ReadOnlyStringProperty messageProperty
messageProperty
in interface Worker<V>
getMessage()
public final ReadOnlyStringProperty titleProperty
titleProperty
in interface Worker<V>
getTitle()
public final <any> executorProperty
getExecutor()
,
setExecutor(Executor)
public final <any> onReadyProperty
getOnReady()
,
#setOnReady()
public final <any> onScheduledProperty
getOnScheduled()
,
#setOnScheduled()
public final <any> onRunningProperty
getOnRunning()
,
#setOnRunning()
public final <any> onSucceededProperty
getOnSucceeded()
,
#setOnSucceeded()
public final <any> onCancelledProperty
getOnCancelled()
,
#setOnCancelled()
public final <any> onFailedProperty
getOnFailed()
,
#setOnFailed()
private static final PlatformLogger LOG
private static final int THREAD_POOL_SIZE
private static final long THREAD_TIME_OUT
private static final java.util.concurrent.BlockingQueue<java.lang.Runnable> IO_QUEUE
private static final java.lang.ThreadGroup THREAD_GROUP
private static final java.lang.Thread.UncaughtExceptionHandler UNCAUGHT_HANDLER
private static final java.util.concurrent.ThreadFactory THREAD_FACTORY
private static final java.util.concurrent.ThreadPoolExecutor EXECUTOR
private final <any> state
private final <any> value
private final <any> exception
private final DoubleProperty workDone
private final DoubleProperty totalWorkToBeDone
private final DoubleProperty progress
private final BooleanProperty running
private final StringProperty message
private final StringProperty title
private final <any> executor
private Task<V> task
private volatile boolean startedOnce
private EventHelper eventHelper
public final Worker.State getState()
public final <any> stateProperty()
Worker
stateProperty
in interface Worker<V>
getState()
public final V getValue()
public final <any> valueProperty()
Worker
valueProperty
in interface Worker<V>
getValue()
public final java.lang.Throwable getException()
getException
in interface Worker<V>
public final <any> exceptionProperty()
Worker
exceptionProperty
in interface Worker<V>
getException()
public final double getWorkDone()
getWorkDone
in interface Worker<V>
Worker.totalWorkProperty()
,
Worker.progressProperty()
public final ReadOnlyDoubleProperty workDoneProperty()
Worker
workDoneProperty
in interface Worker<V>
getWorkDone()
public final double getTotalWork()
getTotalWork
in interface Worker<V>
Worker.workDoneProperty()
,
Worker.progressProperty()
public final ReadOnlyDoubleProperty totalWorkProperty()
Worker
totalWorkProperty
in interface Worker<V>
getTotalWork()
public final double getProgress()
getProgress
in interface Worker<V>
Worker.workDoneProperty()
,
Worker.totalWorkProperty()
public final ReadOnlyDoubleProperty progressProperty()
Worker
progressProperty
in interface Worker<V>
getProgress()
public final boolean isRunning()
public final ReadOnlyBooleanProperty runningProperty()
Worker
runningProperty
in interface Worker<V>
isRunning()
public final java.lang.String getMessage()
getMessage
in interface Worker<V>
public final ReadOnlyStringProperty messageProperty()
Worker
messageProperty
in interface Worker<V>
getMessage()
public final java.lang.String getTitle()
public final ReadOnlyStringProperty titleProperty()
Worker
titleProperty
in interface Worker<V>
getTitle()
public final void setExecutor(java.util.concurrent.Executor value)
public final java.util.concurrent.Executor getExecutor()
public final <any> executorProperty()
getExecutor()
,
setExecutor(Executor)
public final <any> onReadyProperty()
getOnReady()
,
#setOnReady()
public final <any> getOnReady()
public final void setOnReady(<any> value)
value
- the event handler, can be null to clear itprotected void ready()
public final <any> onScheduledProperty()
getOnScheduled()
,
#setOnScheduled()
public final <any> getOnScheduled()
public final void setOnScheduled(<any> value)
value
- the event handler, can be null to clear itprotected void scheduled()
public final <any> onRunningProperty()
getOnRunning()
,
#setOnRunning()
public final <any> getOnRunning()
public final void setOnRunning(<any> value)
value
- the event handler, can be null to clear itprotected void running()
public final <any> onSucceededProperty()
getOnSucceeded()
,
#setOnSucceeded()
public final <any> getOnSucceeded()
public final void setOnSucceeded(<any> value)
value
- the event handler, can be null to clear itprotected void succeeded()
public final <any> onCancelledProperty()
getOnCancelled()
,
#setOnCancelled()
public final <any> getOnCancelled()
public final void setOnCancelled(<any> value)
value
- the event handler, can be null to clear itprotected void cancelled()
public final <any> onFailedProperty()
getOnFailed()
,
#setOnFailed()
public final <any> getOnFailed()
public final void setOnFailed(<any> 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()
void cancelFromReadyState()
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 executeprivate EventHelper getEventHelper()
public final <T extends Event> void addEventHandler(<any> eventType, <any> eventHandler)
T
- the specific event class of the handlereventType
- the type of the events to receive by the handlereventHandler
- the handler to registerjava.lang.NullPointerException
- if the event type or handler is nullpublic final <T extends Event> void removeEventHandler(<any> eventType, <any> eventHandler)
T
- the specific event class of the handlereventType
- the event type from which to unregistereventHandler
- the handler to unregisterjava.lang.NullPointerException
- if the event type or handler is nullpublic final <T extends Event> void addEventFilter(<any> eventType, <any> eventFilter)
T
- the specific event class of the filtereventType
- the type of the events to receive by the filtereventFilter
- the filter to registerjava.lang.NullPointerException
- if the event type or filter is nullpublic final <T extends Event> void removeEventFilter(<any> eventType, <any> eventFilter)
T
- the specific event class of the filtereventType
- the event type from which to unregistereventFilter
- the filter to unregisterjava.lang.NullPointerException
- if the event type or filter is nullprotected final <T extends Event> void setEventHandler(<any> eventType, <any> 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 unregisterjava.lang.NullPointerException
- 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)
protected 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());
}
void checkThread()
void runLater(java.lang.Runnable r)
boolean isFxApplicationThread()