Is the Swing repaint() method still safe to use outside the EDT in Java 7+? Is the Swing repaint() method still safe to use outside the EDT in Java 7+? multithreading multithreading

Is the Swing repaint() method still safe to use outside the EDT in Java 7+?


This is the official reference:

Swing's Threading Policy

In general Swing is not thread safe. All Swing components and related classes, unless otherwise documented, must be accessed on the event dispatching thread.

And the repaint method does not "document otherwise".

To doubly reassure you that you do not need to look any further than an individual method's Javadoc for the definitive answer, see for example how a method's thread safety was documented in Java 6 Javadoc.

Update

Apparently, more clarification is needed as to the distinction between normative specification, descriptive technical articles, and details of any specific implementation. What the Javadoc states is this: there is no guarantee that repaint is a thread-safe method. Incidentally, the often-discussed decision in Java 7 to remove the "thread-safe" designation from most of the Swing API was just that: a change in contract, not implementation.

The specific implementation of repaint in OpenJDK 7 appears to be thread-safe, a fact which has nothing to do with guarantees given by the specification. Code which relies on the thread safety of repaint or other methods is broken and is not guaranteed to behave properly on all Java implementations.


As discussed in Painting in AWT and Swing: Paint Processing,

JComponent.repaint() registers an asynchronous repaint request to the component's RepaintManager, which uses invokeLater() to queue a Runnable to later process the request on the event dispatching thread.

This is a necessary, but not sufficient, condition to establish a happens-before relation between successive calls to repaint(). As a practical matter, you still need to synchronize access to any data that is shared between threads. Without this, there's no way to ensure the visibility of any changes meant to influence the subsequent call to repaint().


I would say it is still thread safe. The repaint() method doesn't change the property of any Swing component.

The repaint() method invokes the RepaintManager. The RepaintManager will then (potentially) combine multiple painting requests into a single paint request. It will then add the paint request to the EDT for processing.