Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronization block and method confusion  RSS feed

 
amithk kumar
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1)question is if i use synchronized method it will acquire the lock for the test object or for both proce and test object.

Because the value are printing correctly when i used synchronized method while calling getVal method from test class

2) If i use synchronized block in getInc and acquire lock for test class for example like this
what will happen automatically var variable of proce class will be synchronized?

here are the classes which i have used


 
Simon Roberts
Author
Ranch Hand
Posts: 176
9
Java Linux Netbeans IDE
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, this is a case of Too Long, Didn't Read, but, since the question has sat idle for a couple of days, let me offer some general info that might be useful.

1) a single use of synchronized will require possession of exactly one lock, never any other number.
2) a synchronized instance method is equivalent to synchronized(this) wrapped around the entire method
3) a synchronized static method on a class MyClass is equivalent to synchronized(MyClass.class)
4) Just because something prints the right value when you try it does not prove it's safe from a threading perspective ;)

HTH
Cheers,
Simon
 
Liutauras Vilda
Marshal
Posts: 4641
318
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
amithk kumar,

As Simon correctly identified, you posted lots of code with inconsistent formatting and without using code tags, which caused your code not being readable, that is likely why you didn't get any help till now.
Please check how to UseCodeTags (<- link to click on), so you'd know next time. I have added them for you this time, also removed unecessary empty lines in between every code line, so it is easier to identify the the separate methods and code blocks. Check this conventions page (<- link to click on) so you could see how the code should be indented and formatted. Document is quite old, from 1999 years, but convention is still used in nowadays.

And welcome to the Ranch
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!