Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static variable Question?

 
Sneha Latha
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Friends,in Java, Can we synchronize static variables ?
 
gaurav abbi
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
synchronized can't be applied to variables
only public, protected, private, static, final, transient & volatile
are permitted
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, welcome to the ranch!

Since you can synchronize on any object, you can synchronize on an object that is referenced by a static variable ...

Since MONITOR is static, all instances of this class will synchronize on the same object. Which might be exactly what somebody needs. Or not.
[ January 25, 2007: Message edited by: Stan James ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

I'm not sure whether you mean synchronize on a static variable (as Stan addressed) or synchronize the variable itself (as gaurav addressed).

To expand on what gaurav said, you can't apply "synchronized" to the variables themselves. But you can make the variables private, and use synchronized getter and setter methods to access them. Alternatively, you could use a synchronized block (as shown in Stan's example).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic