• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Variables can't be synchronized

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
why Variables can't be synchronized? any example ?
 
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You use the synchronized keyword to synchronize access to protect a region of code from concurrent access by multiple threads i.e. methods or portions of a method. It doesn't make sense to protect a variable, because it's not a code block. If you DO want to protect your variables (and only your variables) from concurrent access by multiple threads, use the keyword volatile.

Using volatile variables can be better performance than using small synchronized blocks due to the overhead associated with synchronization.
 
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The reason is because you need to obtain a lock when you synchronize. Since methods and objects have locks, you could synchronize on them. Variable don't have locks.

Examples:
//synchronizing on an instance of the class:
Synchronized(this){}

// Synchonizing on the out stream object:
Synchronized(System.out){}
[ June 01, 2006: Message edited by: Firas Zureikat ]
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Firas Zureikat:
... Since methods and objects have locks, you could synchronize on them. Variable don't have locks...


Not quite. Objects and classes each have locks, but methods do not have locks. To execute a synchronized method, the thread must first obtain the object lock (or class lock if the method is static).
[ June 01, 2006: Message edited by: marc weber ]
 
A wop bop a lu bop a womp bam boom! Tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic