Running Time-Consuming Operations in the Background Mode
- Skill Level Advanced
- Supported Versions JavaFX 1.1
- Key Features Performance
- Last Updated February 2009
The JavaFX code is executed on a single thread known as Event Dispatch Thread, or EDT for the desktop applications, and thus time-consuming operations may cause applications to become unresponsive or sluggish. To avoid undesirable pauses, run long-term operations in asynchronous mode.
A typical example of time-consuming operations is accessing data on the Web. Instead of retrieving and processing data immediately, use the javafx.async.RemoteTextDocument class to load web pages and the onDone function to process the data. Loading will happen on the separate thread and your main application thread will not be blocked.
var data:RemoteTextDocument = RemoteTextDocument {
url: "http://mywebsite.com/some/page.html"
onDone: function (finished) {
System.out.println(data.document);
}
}
Use the javafx.io.http.HttpRequest class to load non-textual data or for thread processing. For example, the Interesting Photos demo employs the HttpRequest class for async loading of images from Flickr. The code is very similar to the previous version, however, the data processing is performed by the onInput function that reads the data from the input stream. Another difference is that the RemoteTextDocument object should explicitly initiate the http request.
var request: HttpRequest = HttpRequest {
location: "http://server.com/page"
method: HttpRequest.GET
onInput: function(input: java.io.InputStream) {
try {
//parse input stream
} finally {
input.close();
}
}
}
request.enqueue();
In addition to the standard capabilities, you can create a custom async operation using the javafx.async.AbstractAsyncOperation class. Refer to the examples in the James Clarke's blog for more information on how to apply an async operation to access a database. Note that this example uses the internal JavaFX classes, which may be changed in the next JavaFX release.