Instead of running intensive tasks into JavaFX Thread
that should be done into a Service
.So what basically is a Service?
A Service is a class which is creating a new Thread
every time you are starting it and is passing a Task to it to do some work.The Service can return or not a value.
Below is a typical example of JavaFX Service which is doing some work and return a
Map<String,String>(
):
public class WorkerService extends Service<Map<String, String>> {
/**
* Constructor
*/
public WorkerService () {
// if succeeded
setOnSucceeded(s -> {
//code if Service succeeds
});
// if failed
setOnFailed(fail -> {
//code it Service fails
});
//if cancelled
setOnCancelled(cancelled->{
//code if Service get's cancelled
});
}
/**
* This method starts the Service
*/
public void startTheService(){
if(!isRunning()){
//...
reset();
start();
}
}
@Override
protected Task<Map<String, String>> createTask() {
return new Task<Map<String, String>>() {
@Override
protected Void call() throws Exception {
//create a Map<String, String>
Map<String,String> map = new HashMap<>();
//create other variables here
try{
//some code here
//.....do your manipulation here
updateProgress(++currentProgress, totalProgress);
}
} catch (Exception ex) {
return null; //something bad happened so you have to do something instead of returning null
}
return map;
}
};
}
}