Search code examples
javaswingserializationserializable

Swing firing listeners during GUI deserialization


Today I've encountered a very nasty bug that involves firing swing listeners during GUI deserialization using the standard Java serialization API. It's a bit difficult to concisely explain how to replicate this behavior, so I've posted a small test case below. This test case does not throw any exceptions, trigger any compiler warnings, and certainly doesn't seem to have a well defined behavior. Is this a bug, gray area in Oracle's package interop documentation, or just something that on-one's tried before?

Just to illuminate my original use-case, I was attempting to automatically update several tabs in an asset-editor upon reloading a configuration component from disk.

package com.ihateswing.ssce;

import java.awt.BorderLayout;

public class SSCE implements Serializable {



    private class Internal extends JPanel {
        private final JComboBox<String> m_cb = new JComboBox<String>();

        Internal(final JComboBox<String> cb) {
            cb.addActionListener(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    DefaultComboBoxModel<String> dcbm = new DefaultComboBoxModel<String>();
                    for (int i = 0; i < cb.getModel().getSize(); ++i) {
                        dcbm.addElement(cb.getModel().getElementAt(i));
                    }
                    m_cb.setModel(dcbm);
                }
            });
            super.add(m_cb);
        }
    }

    private JFrame frame;
    private JComboBox<String> jce = new JComboBox<String>();

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SSCE window = new SSCE();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public SSCE() {
        initialize();
    }

    private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException {
        stream.defaultReadObject();
        jce.setSelectedIndex(0); // <-- Seems to have undefined behavior?
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        jce.setModel(new DefaultComboBoxModel<String>());
        frame.getContentPane().add(new Internal(jce), BorderLayout.NORTH);
        frame.getContentPane().add(jce, BorderLayout.CENTER);

        JButton btnAddRandomItem = new JButton("Break");
        btnAddRandomItem.addActionListener(new AbstractAction() {
            private static final long serialVersionUID = 1L;
            private int i;

            public void actionPerformed(ActionEvent e) {
                try {
                    ((DefaultComboBoxModel<String>) jce.getModel())
                            .addElement(String.valueOf(i++));
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ObjectOutputStream out = new ObjectOutputStream(baos);
                    out.writeObject(SSCE.this);
                    ByteArrayInputStream in = new ByteArrayInputStream(baos
                            .toByteArray());
                    ObjectInputStream oin = new ObjectInputStream(in);
                    oin.readObject();

                    // The line below updates 'Internal' as expected, uncomment
                    // to see...
                    // however with the listener fired from the serialization
                    // method, it breaks?
                    // jce.setSelectedIndex(0);
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        });
        frame.getContentPane().add(btnAddRandomItem, BorderLayout.SOUTH);
    }

}

Sample with output (Clicked 'Break' 5 times)

package com.ihateswing.ssce;

import java.awt.BorderLayout;

public class SSCE implements Serializable {



    private class Internal extends JPanel {
        private final JComboBox<String> m_cb = new JComboBox<String>();

        Internal(final JComboBox<String> cb) {
            cb.addActionListener(new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    DefaultComboBoxModel<String> dcbm = new DefaultComboBoxModel<String>();
                    for (int i = 0; i < cb.getModel().getSize(); ++i) {
                        dcbm.addElement(cb.getModel().getElementAt(i));
                    }
                    m_cb.setModel(dcbm);
                    System.out.println("Set Internal.m_cb's model with " + m_cb.getModel().getSize() + " elements");
                }
            });
            super.add(m_cb);
        }
    }

    private JFrame frame;
    private JComboBox<String> jce = new JComboBox<String>();

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SSCE window = new SSCE();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public SSCE() {
        initialize();
    }

    private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException {
        stream.defaultReadObject();
        jce.setSelectedIndex(0); // <-- Seems to have undefined behavior?
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final Internal internal = new Internal(jce);
        jce.setModel(new DefaultComboBoxModel<String>());
        frame.getContentPane().add(internal, BorderLayout.NORTH);
        frame.getContentPane().add(jce, BorderLayout.CENTER);

        JButton btnAddRandomItem = new JButton("Break");
        btnAddRandomItem.addActionListener(new AbstractAction() {
            private static final long serialVersionUID = 1L;
            private int i;

            public void actionPerformed(ActionEvent e) {
                try {
                    ((DefaultComboBoxModel<String>) jce.getModel())
                            .addElement(String.valueOf(i++));
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ObjectOutputStream out = new ObjectOutputStream(baos);
                    out.writeObject(SSCE.this);
                    ByteArrayInputStream in = new ByteArrayInputStream(baos
                            .toByteArray());
                    ObjectInputStream oin = new ObjectInputStream(in);
                    oin.readObject();
                    System.out.println("After returning, Internal.m_cb's model size is " + internal.m_cb.getModel().getSize() + " elements");
                    // The line below updates 'Internal' as expected, uncomment
                    // to see...
                    // however with the listener fired from the serialization
                    // method, it breaks?
                    // jce.setSelectedIndex(0);
                } catch (Throwable t) {
                    t.printStackTrace();
                }
            }
        });
        frame.getContentPane().add(btnAddRandomItem, BorderLayout.SOUTH);
    }

}

Set Internal.m_cb's model with 1 elements
Set Internal.m_cb's model with 1 elements
After returning, Internal.m_cb's model size is 1 elements
Set Internal.m_cb's model with 2 elements
After returning, Internal.m_cb's model size is 1 elements
Set Internal.m_cb's model with 3 elements
After returning, Internal.m_cb's model size is 1 elements
Set Internal.m_cb's model with 4 elements
After returning, Internal.m_cb's model size is 1 elements
Set Internal.m_cb's model with 5 elements
After returning, Internal.m_cb's model size is 1 elements

Solution

  • I don't think you are updating what you think you are updating. Here is the same output, if you append to each println m_cb.hashCode(). Note that below, the "Set..." error message indicates that the model is being set on a different instance of m_cb each time.

    Set Internal.m_cb's model with 1 elements: 44160343
    Set Internal.m_cb's model with 1 elements: 1436306574
    After returning, Internal.m_cb's model size is 1 elements: 44160343
    Set Internal.m_cb's model with 2 elements: 2094948113
    After returning, Internal.m_cb's model size is 1 elements: 44160343
    Set Internal.m_cb's model with 3 elements: 915510800
    After returning, Internal.m_cb's model size is 1 elements: 44160343
    Set Internal.m_cb's model with 4 elements: 853795873
    After returning, Internal.m_cb's model size is 1 elements: 44160343
    Set Internal.m_cb's model with 5 elements: 616759228
    After returning, Internal.m_cb's model size is 1 elements: 44160343
    Set Internal.m_cb's model with 6 elements: 1385385632
    After returning, Internal.m_cb's model size is 1 elements: 44160343
    Set Internal.m_cb's model with 7 elements: 1283006722
    After returning, Internal.m_cb's model size is 1 elements: 44160343
    

    A new instance of m_cb is created in each serialization, and you are setting its model-- but those new combo boxes are not displayed in your frame.