Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread Safety

 
Rachit Kumar Saxena
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5126
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic