my dog learned polymorphism*
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Thread Safety" Watch "Thread Safety" New topic
Author

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
Sheriff

Joined: Aug 22, 2010
Posts: 3610
    
  60

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
Bartender

Joined: May 03, 2008
Posts: 4530
    
    5

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: 416
    
    2

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
 
wood burning stoves
 
subject: Thread Safety