Why should Swing components be available only in the Event Manager topic?

The above statement is mentioned in javadoc SwingWorker.

In the application, I saw that a lengthy background task runs in a separate thread and updates the interface also without problems (a link to the Swing component was available).

Maybe something bad can happen?

+5
source share
2 answers

This is because the Java memory model does not guarantee that the memory write by one thread will be visible to other threads unless you use some form of synchronization. For performance and simplicity, Swing is not synchronized. Therefore, records from other streams will never be seen by EDT.

The application you saw can work most of the time, and it can even work all the time in some environments. But when that doesn't work, it's really weird that it's hard to reproduce.

+6
source

All Swing components are implemented for access from one thread (event dispatch thread). Thus, there is no protection against concurrent access and simultaneous changes of variables and fields.

If you're lucky, everything works well. But you cannot rely on it, and the same code can have serious problems the next time you run it.

A simple example:

The JLabel drawing procedure contains the following (simplified) code (taken from the BasicLabelUI class):

  # assume your label is enabled Icon icon = (label.isEnabled()) ? label.getIcon() : label.getDisabledIcon(); # what happens if another thread calls label.setEnabled(false) at this point? if (icon != null) { icon.paintIcon(c, g, paintIconR.x, paintIconR.y); } if (label.isEnabled()) { paintEnabledText(label, g, clippedText, textX, textY); } else { paintDisabledText(label, g, clippedText, textX, textY); } 

For example, if you call setEnabled () from streams other than EDT, you might get a shortcut with the icon turned on, but the colored text is turned off.

+5
source

Source: https://habr.com/ru/post/1214223/


All Articles