0

I have a Swing application that runs on multiple threads, I created the Swing components on the EDT. An Executor launches threads that insert text to the JTextArea at some point. However, InvokeLater doesn't always do the appending, unlike InvokeAndWait. As I gathered it's aynchronous, non-blocking, but still should do the appending. How can it be?

Thanks

Jhonny
  • 587
  • 1
  • 6
  • 17
  • They both append to the end of the queue. I'm not sure what you're getting at? – WalterM Nov 14 '15 at 13:34
  • 1
    `"InvokeLater doesn't always do the appending..."`, you've likely got a bug somewhere in your code, and likely doesn't involve invokeLater per se, but is being unmasked by it. Time to do some debugging. – Hovercraft Full Of Eels Nov 14 '15 at 14:08
  • Been doing that for so long, but thanks for clearing that up, guess the error is somewhere else then. – Jhonny Nov 14 '15 at 14:34
  • 1
    @HovercraftFullOfEels is likely right about the problem _being unmasked_. When something _doesn't always_ work, suspect errant synchronization. – trashgod Nov 14 '15 at 17:02

1 Answers1

4

Using EventQueue.invokeLater() to update a component's model from another thread is a necessary—but not sufficient—condition for correct synchronization. You are still required to synchronize access to any shared data. In this example, the display() parameter s is a final reference to an immutable String; it can be accessed safely in display() without further synchronization. If you have a final reference to a mutable object, consider a thread-safe collection. You can look for violations using one of the approaches cited here. Alternatively, consider a SwingWorker to host the background task, for example.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • 1
    This is about as good an answer as can be given, given the data presented. Hopefully the OP will present more specific data so you can give more specific advice. Thanks for the answer! – Hovercraft Full Of Eels Nov 14 '15 at 22:58