0

I haven't made Thread myself. I have one timeline that runs from the beginning to the end of the program which is as follows:

Timeline timeline = new Timeline(
        new KeyFrame(Duration.millis(TIMELINE_DELAY), event -> {
            intrudersList.forEach(Intruder::action);
            towersList.forEach(Tower::action);
            otherActivesList.forEach(Active::action);
        }));
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();

And when the die method of the Intruder class is called, i get this Concurrent Modification Exception.

First, I don't actually understand how timeline works! Does it create new Threads itself or what? and what will happen if for example we have a timeline that does a task every 10 seconds and that task takes 15 seconds to be done! And second indeed: How can i get this fixed!?

public void die() {
    this.getCell().getContent().remove(this);
    TimeLine.getInstance().removeIntruder(this);
    System.out.println("death of intruder at: " + cell);
}
yukashima huksay
  • 5,834
  • 7
  • 45
  • 78
  • 2
    Simply wrap the content of `die` into a Platform.runLater(() -> { ... }) block. – DVarga Jul 06 '16 at 15:11
  • thanks. then, when will the lambda get invoked exactly?! – yukashima huksay Jul 06 '16 at 15:53
  • Maybe you are trying to edit a List while you iterate over it? What is `Intruder::action` doing? – aw-think Jul 06 '16 at 19:20
  • 1
    Please post the stack trace. Which line is actually throwing the exception? The `Timeline` does not create any new threads, and the event handler is executed on the (already running) FX Application Thread. There's no reason at all to believe this is a threading issue. – James_D Jul 06 '16 at 20:18

2 Answers2

1

Check out the docs. This exceptions typically happens when a list is modified while that is not allowed.

This can occur when 2 different threads are trying to modify the same list concurrently, but more often it means you are trying to modify a list while iterating over it (which is not allowed).

Oliver Jan Krylow
  • 1,758
  • 15
  • 22
0

Many thanks to @DVarga, This is what the problem was and how i fixed it: the problem was that I was modifying the intrudersList in removeIntruder , while iterating on it in KeyFrame. And I solved it by wrapping the body of the removeIntruder method in a Platform.runLater(() -> { ... }) block. I Guess what Platform.runLater does is that it waits until the list is modifyable and then modifies it.

yukashima huksay
  • 5,834
  • 7
  • 45
  • 78