Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

transient and volatile variables

 
Satish Ray
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In Kathy sierra SCJP 1.5 book i have read that transient and volatile modifiers apply only for instance variables.

Might be they are irrelevant in the following sense as I think:
1)transient ->during serialization only the object state is flattened and the class variables(I mean static varibles) wont come into picture here.
2)volatile->is meaningful only for instance varibles and not static variables, as only the objects state is being protected from any simultaneous modification.

Correct me if I am wrong.

I also compiled and ran the below program using static-transient, static-volatile combination of variables. it is perfectly compiling and running fine.

class A{
static volatile int x;
static transient int y;

public static void main(String[] args){
A a = new A();
System.out.println(x);
System.out.println(a.x);
System.out.println(y);
System.out.println(a.y);
}
}

Can any body please clarify my doubt?
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13064
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are a number of uses of modifiers that do not cause compiler errors or runtime errors which are nevertheless totally meaningless - not applicable. So, what is your doubt? Did you expect the compiler to object?

Bill
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't see why volatile wouldn't be useful for class variables.

I don't have the book, but perhaps what was meant is that those modifiers don't apply to local variables?
 
Satish Ray
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

My doubt is whether we can use transient and volatile variables respectively along with static modifier legally? or is it that there is no necessity for using transient and volatile modifiers along with static modifier?
 
Henry Wong
author
Marshal
Pie
Posts: 21212
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The volatile modifier is perfectly legal for both instance and static variables -- as what it does, is specify how it should behave.

The volatile modifier doesn't make sense for local variables because local variables are not accessable by multiple threads.

The transient modifier doesn't make sense for static variables, because class variables are not serialized.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic