File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Thread Safety Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Thread Safety" Watch "Thread Safety" New topic

Thread Safety

Rachit Kumar Saxena
Ranch Hand

Joined: Dec 24, 2011
Posts: 50
What do the terms Thread Safety in java mean?We say awt components are thread safe but swing components arenot.What does it mean?
Martin Vajsar

Joined: Aug 22, 2010
Posts: 3733

Generally, a class is Thread Safe when its state remains valid even when its methods are called simultaneously from different threads. Class has to be specifically designed to be thread safe, usually by employing some synchronization mechanism internally, or by making it immutable. Immutable classes do not change their state at all and cannot therefore be brought into invalid state after construction, regardless of how many threads access them. This is one of the reasons why immutable classes are wonderful.

You can obtain many interesting links by searching for Java Thread Safety. Why Swing was not designed thread-safe is explained here.
Darryl Burke

Joined: May 03, 2008
Posts: 5115

Rachit Kumar Saxena wrote:We say awt components are thread safe

We do? Can you quote a reference for that? I'd be interested to read about it in more detail.

luck, db
There are no new questions, but there may be new answers.
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 443

The simple version ..

Swing methods are intended to be invoked only from the one and only EDT thread, they have no locking as this was considered slow among other things and multithreaded GUI's hard to design correctly. If you call a swing method from off the EDT thread all bets are off, though it will probably (appear to) work unless they have a guard (don't do it though).

If you say a class is thread safe you can call it from any thread without worrying about synchronization and the Java memory model (gross horrible simplification), in Swing you would use the SwingUtilities to execute your task on the EDT rather than call any method from your thread which your statements claims is ok for AWT (I'd have to check).

AWT is older than swing hence the difference.

"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
I agree. Here's the link:
subject: Thread Safety
It's not a secret anymore!