Win a copy of TensorFlow 2.0 in Action this week in the Artificial Intelligence and Machine Learning forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

Synchronize on variable inside a method

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Inside a class this method has a synchronize block inside it:

Will this type of synzhronization effective as it is using the method's variable as a lock instead of the instance variable?
TIA
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think about how another thread would be able to access the object on which the locking takes place. (This could be a rather borderline case, the string you are using will be in the string pool, so perhaps another thread could just access the same object. There's probably no way you could be certain because whatever happens is implementation dependent.) So use an object which is explicitly shared between threads. Don't forget that we lock shared objects, not the variables referring to them.
[ May 12, 2004: Message edited by: Barry Gaunt ]
 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Barry, You have an excellent point about the synchronization object being in the string literal pool.
I got curious and wrote a test program to try it out. And you are 100% correct! All the threads are synchronizing on the same object.
That is an excellent catch!
 
How do they get the deer to cross at the signs? Or to read this tiny ad?
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic