Search code examples
javamultithreadingswingjtableabstracttablemodel

AbstractTableModel updating from different threads


I have class which is actually list of some data and it extends AbstractTableModel. Data in this class are stored inside thread-safe arraylist.

However if I want to add some data, lets say I have this method inside class extending AbstractTableModel:

public void addData(Data data){
  threadSafeArrayList.add(data);
  fireTableRowsInserted(threadSafeArrayList.size()-1;threadSafeArrayList.size());
}

I should call everything what is inside this method on EDT. However when some other thread is looping through this list to get some data at same time as EDT wants to add data to this list. Then EDT is blocked.

What is best pratice to add/delte data to/from table model that is used by many other threads expect using SwingWorker.


Solution

  • expect using SwingWorker.

    I too would expect to use a SwingWorker, but you may have meant except SwingWorker.

    The best practice is to update the TableModel on the event dispatch thread as shown here in the process() implementation of JDBCWorker, a subclass of SwingWorker.

    Alternatively, you can update the table's model using EventQueue.invokeLater(), as shown here, but the approach is tedious and error prone. See the comments for details.