aspose file tools*
The moose likes Beginning Java and the fly likes Static variable Question? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Static variable Question?" Watch "Static variable Question?" New topic
Author

Static variable Question?

Sneha Latha
Greenhorn

Joined: Jan 25, 2007
Posts: 3
Friends,in Java, Can we synchronize static variables ?
gaurav abbi
Ranch Hand

Joined: Jan 05, 2007
Posts: 108
synchronized can't be applied to variables
only public, protected, private, static, final, transient & volatile
are permitted


thanks,<br />gaurav abbi
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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 ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

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).


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static variable Question?