This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

i need smart solution pleeease  RSS feed

 
Nada Mohammed
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello every body ,
i have the following code :
class a {
int value=0 ;
synchronized void changeValue(int c) { vlaue= c ;}
synchronized int returnValue() {return value ; }
synchronized boolean compareVlaue(int c) {
if (c==value) return true ;
else flase ;
}
..........
} //class a
as you see all methods should be syncronized .My question is there any way to avoid using synchronized keyword many times and rewarded by simple structure .
I need simple structure and high performance
Thanks alot
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the code you gave, you can safely omit the synchronized keyword and declare the "value" variable volatile. The volatile modifier will ensure that a change made in one thread is immediately visible to all other threads.
Note two things, however. First, volatile will not work properly for methods that access "value" more than once (e.g. read - modify - write). Second, I'm not convinced that synchronizing at the class A level actually buys you anything, it is quite likely that other classes using A are performing operations that need to be synchronized as a whole. If this is true, either the synchronization needs to be pulled out of A, or the operations performed should be incorporated as methods into A. In both cases a simple volatile modifier won't cut it anymore.
- Peter
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!