Two Laptop Bag
The moose likes Beginning Java and the fly likes Transient & Volatile Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Transient & Volatile" Watch "Transient & Volatile" New topic

Transient & Volatile

Tom Keith

Joined: Mar 26, 2002
Posts: 24
Hi All,
Can somebody tell me what is the purpose of using
Transient & Volatile keywords? and also how and where can it be used in a java program? Does it have any significance?
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Tom,
Transient comes into play regarding serialization. A transient variable will not be serialized. This is important, because some class state variables don't need to be persistent. For example, suppose you had the following class:

The currentTemperature will probably be different when the class is restored. Therefore, we don't want to waste file space saving a variable that will change anyway.
Volatile relates to threading and optimization. When you declare a variable to be volatile, you are telling the compiler not to try and optimize (sharing) it regarding threading. I don't really have an example for this because I have not used it.
David Weitzman
Ranch Hand

Joined: Jul 27, 2001
Posts: 1365
I think this is one of the uses of volatile - to solve the memory issues of double-checked locking. I could be wrong though, so please don't trust me.

[ April 01, 2002: Message edited by: David Weitzman ]
Mike Birken

Joined: Dec 28, 2001
Posts: 20
Anyone care to comment on strictfp?
- Mike
David Weitzman
Ranch Hand

Joined: Jul 27, 2001
Posts: 1365
Strictfp is just like volatile -- you'll probably never actually need to use it. Actually you're more likely to use volatile. It just means that arithmatic will be done exactly according to some standard or other (a standard that has also been implemented in other languages like C++). With strictfp, the answer to 345/235.63 will always be exactly the same no matter what vitual machine and operating system you calculate it on. Without strictfp, there's an allowed margin of error. It's sort of the counterpart to the java.lang.StrictMath. Just another feature that will never be used.
I agree. Here's the link:
subject: Transient & Volatile
It's not a secret anymore!