• Post Reply Bookmark Topic Watch Topic
  • New Topic

Making JTable updates threadsafe and keeping GUI responsive  RSS feed

 
Jared Cope
Ranch Hand
Posts: 243
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Just wondering if someone can offer some advice on the following problem. I hope I explain it well enough.

I have 1 thread that automatically updates a JTable with new entries from a database. Every 10 seconds it queries for new entries and adds them to the table as they become available.

Another thread does a forced update of the table when the user presses a button, that is, queries the database at 'button press time' and replaces entries in the table.

I am worried about the JTable potentially being updated in a way that is not thread safe, and bad for the health of the GUI.

I know that updates to the GUI (in this case the JTable view) need to execute in the AWT thread, but if the database code appears in this thread it sometimes makes the interface freeze because the query takes a long time to complete and can't redraw the screen. The user can't go off and do other things. Worse still if the network communication causes an error and unwinds the AWT thread ...

However, I am worried about updating the JTable outside the AWT thread (the database code goes in a Runnable and executed in a new thread) because this could cause multiple update problems for the JTable. I have seen 'ghosting' of the JTable. But this approach always makes the GUI responsive.

Has anyone faced a problem like this before? What worked for you? Is there a good design pattern for this?

Cheers, Jared.
 
Don Kiddick
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think you have to update the model in the AWT thread....therefore you could implement a threadsafe TableModel.

Alternatively use a SwingWorker SwingWorker. Your db code goes in the construct method and is executed on a seperate thread. Your "updating the jtable" code goes in the finished method. This gets executed on the AWT thread.

I would go for the SwingWorker method, it sounds easier.
hth, D.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!