0

In the final minutes of a Java lesson about threads, our professor suggested us to pay specific attention when developing complex Swing-based applications, since Swing is not thread-safe. Is there any specific reason behind this? Swing is not thread safe due to a design decision, or due to software limitations? Thanks in advance for the answer.

kernel_panic
  • 119
  • 11
  • See also [*java.awt.EventQueue.invokeLater explained*](http://stackoverflow.com/q/22534356/230513). – trashgod Sep 03 '16 at 15:36

2 Answers2

6

Javin Poul's programming blog Java Revisited has a great blog post about this:

Why Swing is not thread-safe in Java?

It's the decision taken by there designer, at that time. Since making an API thread-safe takes a lot of work, and it's often based upon benefit you get. Since GUI screens are mostly updated in response of user action e.g. when user click a button, and since events are handled in the same Event dispatcher thread, it's easy to update GUI on that thread. It's very rare, when an update request for GUI comes from a different thread e.g. may be once a network request is complete or a file is loaded.

Community
  • 1
  • 1
Daniel
  • 10,641
  • 12
  • 47
  • 85
5

Most, if not all, GUI toolkits are not thread-safe (Qt, Swing, Winforms...). Creating a thread-safe GUI toolkit would add too much unneccesary complexity. In most cases, it is sufficient to create a quick event handler.

For instance, we have a button that calculates a week day 40 days from today, converts Celsius temperature to Fahrenheit, or computes the sum of provided values. All these operations can be calculated fairly quickly. If Swing was thread-safe, these calculations would be placed inside separate threads, which would be clearly an overkill. So instead of this, we put only long-running tasks into threads, such as burning a DVD, calculating a very complex task, downloading a huge file etc.

See this answer: Why are most UI frameworks single threaded?

Community
  • 1
  • 1
Jan Bodnar
  • 10,969
  • 6
  • 68
  • 77