I have a Trade
object and whenever it is constructed, it kicks off a task in the background (i.e. say download currentPrice) and start running every 10 seconds.
When the Trade
object is created, it is also added to a ObservableList
.
Problem: When I delete the object from the ObservableList, I can see that the task (download currentPrice) is still running in the background, although the object is not in the ObservableList
anymore.
My goal is to delete the object forever and stop its background task from running as well.
public class Trade{
....
private final ScheduledService<Number> priceService = new ScheduledService<Number>() {
@Override
public Task<Number> createTask(){
return new Task<Number>() {
@Override
public Number call() throws InterruptedException, IOException {
return getCurrentPriceFromGoogleFinance();
}
};
}
};
public Trade(){
priceService.setPeriod(Duration.seconds(10));
priceService.setOnFailed(e -> priceService.getException().printStackTrace());
this.currentPrice = new ReadOnlyDoubleWrapper(0);
this.currentPrice.bind(priceService.lastValueProperty());
startMonitoring();
}
public ReadOnlyDoubleProperty currentPriceProperty(){
return this.currentPrice.getReadOnlyProperty();
}
public final double getCurrentPrice(){
return currentPriceProperty().get();
}
// multi-threading
public final void startMonitoring() {
priceService.restart();
}
public final void stopMonitoring() {
priceService.cancel();
}
....
}
If I understand garbage collector right, your object will live for some time before it gets collected even after you remove it from your list.
To stop the task, add ListChangeListener to your ObservableList
. You can get removed Trade
and call stopMonitoring()
on it. That could hopefuly stop the task.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments