• Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronizing access w/Multithreaded GUI

 
Siegfried Heintze
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let us suppose I am writing a screen scraper with a front end implemented using Swing.

If I create a thread to go scrape those screens, can that thread access the controls (like JList) to remove entries from it? How would I protect it from multiple threads accessing the same GUI component at the same time?

I don't think the keyword synchonrized would be sufficient here as that only synchronizes a single method and I need to be assured that all the methods of an existing component (that I did not write) are synchronized so that if anyone one thread is calling any function of that component, all other threads must block until that first thread is don.

In other programming environments, like C++ with windows (or even perl), I can make the main (parent) thread block on multiple mutexes/semephores as well as the message pump and the main thread can service all the controls on behalf of the child threads by having the child threads send windows messages or set mutexes. I don't believe this is possible with Java. Is this correct?

So how can I be assured that only a single thread is accessing a GUI component at any one time?

Thanks,
Siegfried
 
Dushy Inguva
Ranch Hand
Posts: 264
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
// Asynchronous, the current thread will NOT wait until the method is invoked
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Perform GUI update operation
}
});

// Synchronous, the current thread will wait until the end of the run() method
javax.swing.SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
// Perform GUI update operation
}
});

If you want very fine grained access to thread locking, semaphores and mutexes, you can use the Doug Lea's library if you're running on J2SE 1.4 or below (a version of this is included in J2SE 1.5, look in java.util.concurrent package)
 
Scott Delap
author
Ranch Hand
Posts: 73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Siegfried,

I normally don't plug my own stuff but I will in this case. The sample chapter of my book Desktop Java Live covers threading in Swing and is freely available on the SourceBeat website. It explains a number of ways to interact properly in regards to Swing and threading. I think glancing over it will answer most of your questions.

Scott Delap
ClientJava.com
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!