hexaquark
hexaquark

Reputation: 941

Swing–JavaFX Interoperability ConcurrentModificationException bug

I have spent the last 3 days (20+ hours) trying to solve this ConcurrentModificationException bug. I am trying to migrate my pretty large Java project to JavaFX and I am having trouble with managing Swing–JavaFX Interoperability and Threads, since I want my program to be hybrid in that respect.

The Bug

The Bug arises when I click sufficiently fast on the Add Particle button (but also from multiple other sources in my main project, other buttons also produce the same error). I get the following stacktrace

Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
        at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1043)
        at java.base/java.util.ArrayList$Itr.next(ArrayList.java:997)
        at MainPanel$2.actionPerformed(MainPanel.java:40)
        at java.desktop/javax.swing.Timer.fireActionPerformed(Timer.java:317)
        at java.desktop/javax.swing.Timer$DoPostEvent.run(Timer.java:249)
        at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
        at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
        at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
        at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
        at java.base/java.security.AccessController.doPrivileged(Native Method)
        at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
        at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
        at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
        at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
        at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
        at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
        at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
        at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

enter image description here

Here follows the most Minimally Reproducible Example (MRE) of my project that I can provide, with a Github link here :

testProjectFx.fxml

(FXML file)

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1" fx:controller="SampleController">
   <children>
      <BorderPane fx:id="mainPanel" prefHeight="318.0" prefWidth="535.0" />
      <Button fx:id="addParticle" layoutX="26.0" layoutY="347.0" mnemonicParsing="false" text="Add Particle" />
   </children>
</AnchorPane>

SampleController.java

(FXML Controller file)

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;

public class SampleController {

    @FXML
    private BorderPane mainPanel;

    @FXML
    private Button addParticle;

    public void initializeButtons(MainPanel mainPanel) {
        addParticle.addEventHandler(ActionEvent.ACTION, event -> mainPanel.addParticle(
            100, 5
        ));


    }

}

App.java

(Main class that extends Application).

import javafx.application.Application;
import javafx.embed.swing.SwingNode;
import javafx.fxml.FXMLLoader;
import java.awt.Color;

import javax.swing.SwingUtilities;

import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class App extends Application{
    public static void main(String[] args) {
        launch(args);
    }

    public static SampleController controller;

    @Override
    public void start(Stage stage) throws Exception {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("testProjectFx.fxml"));
            Parent root = loader.load();

            controller = (SampleController) loader.getController();

            Scene scene = new Scene(root, 600 , 400);

            BorderPane scenePanel = (BorderPane) scene.lookup("#mainPanel");
            SwingNode swingNode = new SwingNode();
            MainPanel mainPanel = new MainPanel();

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    mainPanel.setSize(535, 318);
                    mainPanel.setBackground(Color.black);
                    mainPanel.physicsTimer.start();
                    mainPanel.fpsTimer.start();
                    swingNode.setContent(mainPanel);
                }
            });
            scenePanel.setCenter(swingNode);


            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    mainPanel.initializeParticles(15, 100 ,5);
                    controller.initializeButtons(mainPanel);
                }
            });
           
            
            stage.setTitle("FXML Welcome");
            stage.setScene(scene);
            stage.show();

        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

MainPanel.java

(JPanel where the painting occurs)

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Arc2D;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JPanel;
import javax.swing.Timer;

public class MainPanel extends JPanel{

    static Random rand = new Random();
    static ArrayList<Particle> particleList = new ArrayList<Particle>();
    static int timeTick = 1000/60; //fps normal

    /* 
     * Timer that updates the screen every at 60 FPS. 
     */
    Timer fpsTimer = new Timer(timeTick, new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
                for(Particle p : particleList) {
                    p.x += p.vx;
                    p.y += p.vy;
                }
            repaint();
        }
    });

    /* 
     * Timer that updates the physics every 1 millisecond.
     */
    Timer physicsTimer = new Timer(1 , new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
                for(Particle p1 : particleList) {       
                    for(Particle p2 : particleList) {
                        if(p1 == p2) continue;

                        // p1.edgeCollision(p2);
                        // applyForces(p1, p2);
                        // applyCollision(p1, p2);
                    }
                    p1.x += p1.vx;
                    p1.y += p1.vy;
                }   
        }
    });

    /* 
     * Function that initializes some particles on the canvas at the beggining.
     */
    public void initializeParticles(int numberOfParticles, int mass, int charge) {

        for(int i = 0 ; i < numberOfParticles ; i++) {
            int xPos;
            int yPos;
            do {
                xPos = rand.nextInt(100)+25;
                yPos = rand.nextInt(100)+25;
                Particle p = new Particle(xPos, yPos, 0, 0,mass, charge); //mass charge at end
                particleList.add(p);
            }while(!particleAlreadyExists(xPos, yPos));
            
        }
    }

    /* 
     * Draw the particles on the canvas.
     */
    public void paintComponent(Graphics g) {
        
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        for(Particle particle : particleList) {
            g2d.setColor(Color.WHITE);
            Shape circle = new Arc2D.Double(particle.x, particle.y, particle.width, particle.height,
                    0 , 360, Arc2D.CHORD);
            g2d.fill(circle);
        }
    }

    /* 
     * Checks if a particle already exists at the generated position.
     */
    public boolean particleAlreadyExists(double x, double y) {
        
        boolean particleExistsAlready = false;
        for(Particle particle : particleList) {
            if(x >= particle.x-particle.width && x <= particle.x+ 2*particle.width &&
                    y >= particle.y-particle.height && y <= particle.y + 2*particle.height) {
                particleExistsAlready=true;
                break;
            }
        }
        return particleExistsAlready;
        
    }

    public void addParticle(int mass, int charge) {
        initializeParticles(1, mass, charge);
    }

}

Particle.java

(Particle object class)

import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;


public class Particle{
    double x, y;
    double width, height;
    double mass;
    double vx, vy;
    int charge;
    public double radius = 0;
    public double centerX = 0;
    public double centerY = 0;
    static Random rand = new Random();

    public Particle(double x, double y, double velX, double velY,double mass, int charge) {
        this.x = x;
        this.y=y;
        this.width=mass/10;
        this.height=mass/10;
        this.vx=velX;
        this.vy = velY;
        this.mass=mass;
        this.charge = charge;
        this.radius = this.width/2;
        this.centerX = this.x + (this.width/2);
        this.centerY = this.y + (this.height/2);
    }


    public static double velInit() {
        double val;
        if(rand.nextBoolean()) {
            val = rand.nextDouble()*0.5;
        } else {
            val = -rand.nextDouble()*0.5;
        }
        return val;
    }

    public void reinitializeVel(ArrayList<Particle> particles) {
        for(Particle p : particles) {
            p.vx = velInit();
            p.vy = velInit();
            
        }
        
    }
}

Things I Have Tried

I tried wrapping parts of my code with

Platform.runLater(new Runnable() { });

and

SwingUtilities.invokeLater(new Runnable() { });

as described in Oracle's documentation but with no success. There are so many combination possible for that and every one of them seems to make my code behave differently (and wrongly).

I have tried so many combinations that at this point I believe that wrapping with these two functions may not even be the solution.

Does anyone know what I am doing wrong ?

Upvotes: 0

Views: 180

Answers (2)

c0der
c0der

Reputation: 18792

While their might be other issues with the code, the root cause for ConcurrentModificationException is the attempt to iterate over a collection (in this case an ArrayList) while changing the same collection. This is not allowed as stated here:

 it is not generally permissible for one thread to modify a Collection while 
 another thread is iterating over it. 

In the code posted initializeParticles modifies particleList by adding elements to it: particleList.add(p); while paintComponent as well as physicsTimer and fpsTimer all iterate over the same collection using for(Particle particle : particleList)

While there are several ways to overcome this issue the simplest would be to simply change all iterations over particleList to the form:

for(int i=0; i< particleList.size(); i++) {
   Particle p = particleList.get(i);
   .........
}

Upvotes: 2

Beowolve
Beowolve

Reputation: 558

You are calling JavaFX functions from the swing and vice versa. Wrapping code with Platfrom.runlater and SwingUtilities.invokeLater is the correct way if you need javafx/swing communication, but you need to do it the right way ;).

Lets start with App.java SwingNode and controller are not JavaFX components, but are called with SwingUtilities, can't be right.

Should look like this:

        SwingUtilities.invokeLater(() -> {
            mainPanel.setSize(535, 318);
            mainPanel.setBackground(Color.black);
            mainPanel.physicsTimer.start();
            mainPanel.fpsTimer.start();
            mainPanel.initializeParticles(15, 100 ,5);
        });
        
        scenePanel.setCenter(swingNode);
        swingNode.setContent(mainPanel);
        controller.initializeButtons(mainPanel);

Your main error comes from manipulating particleList in the javafx thread while your swing part is iterating the list in the paint functions.

Wrapping your initializeParticle function inside a SwingUtilities.invokeLater() function should fix that.

public void initializeParticles(int numberOfParticles, int mass, int charge) {
    SwingUtilities.invokeLater(() -> {
        for (int i = 0; i < numberOfParticles; i++) {
            int xPos;
            int yPos;
            do {
                xPos = rand.nextInt(100) + 25;
                yPos = rand.nextInt(100) + 25;
                Particle p = new Particle(xPos, yPos, 0, 0, mass, charge); //mass charge at end
                particleList.add(p);
            } while (!particleAlreadyExists(xPos, yPos));
        }
    });
}

However this is very ugly code and you shouldn't mix this two frameworks that way.

Upvotes: 1

Related Questions