0

I need to update some cells of a JTable at a fixed interval within a separate thread from the event dispatch thread. The other cells can only be updated by the event dispatch thread so that the two threads will never update the same cell.

Once you change the data of a JTable, a common way is to call fireTableRowsUpdated() to repaint the JTable. Normally, you call fireTableRowsUpdated() within the event dispatch thread, but can I call it within another thread? If so, is fireTableRowsUpdated() thread-safe, too? There's a chance that the JTable is updated concurrently.

Tom Tucker
  • 11,676
  • 22
  • 89
  • 130

2 Answers2

3

From the documentation for JTable:

Warning: Swing is not thread safe. For more information see Swing's Threading Policy.

This links to the following:

In general Swing is not thread safe. All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread.

And more to the point of your question:

This restriction also applies to models attached to Swing components. For example, if a TableModel is attached to a JTable, the TableModel should only be modified on the event dispatching thread.

Now, it just so happens that you can get away with doing a lot of things that violate this policy. But why do that when it's easy enough to create a SwingWorker and guarantee that your code is thread-safe?

parsifal
  • 646
  • 3
  • 4
2

Use SwingUtilities.invokeLater() instead of SwingWorker if you just want to pass execution to Event Dispatcher Thread

More about SwingUtilities.invokeLater

Community
  • 1
  • 1
BlacKow
  • 281
  • 2
  • 12