• Post Reply Bookmark Topic Watch Topic
  • New Topic

keyword "synchronized"

 
ratul banji
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
Before which of the following can the keyword "synchronized" be placed, without causing a compile error.
Choices:
1. class methods
2. instance methods
3. variables
4. classes
Answer is 1 and 2 .It's cool.
But wht. about ch. 3
I compiled and ran it works. Although choice 3 is not a sensible thing to choose.
CAN synchronized KEY WORD USED B4 VARIABLES !!!
THANKS IN ADVANCE.
This is my 1st post in this forum....expecting good response.
<marquee> Ratul Banerjee </marquee>
 
Marcela Blei
Ranch Hand
Posts: 477
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ratul:Choice 3 isn�t correct, could you please write the code you compile?
Remember that synchronized keyword could be use in a statement too. Look here: http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#255769
Also note that when you want to protect your variables from modifications you make them private and put it�s modifications in a synchronized block or statement.
Also look at this: http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#36930
for learning in which circunstances you may use the volatile keyword for class fields.

[This message has been edited by Marcela Blei (edited April 24, 2001).]
 
Ganapathi Srinivasan
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi..
The keyword synchronized is meant for a thread to get an exclusive right to work on an object at a point of time. So that means that any object can be locked.
So if u r having a synchronized block, u have to mention the object on which u want the lock.
Even in ur code i think the variable that u had synchronized block on would be an object that is derived from java.lang.object
As far as i feel u cannot put synschronized tag on a primitive data type like int.
Example
#1) String sl_Name = "Hi";
.
.
.
synchronized(sl_Name){
for(int i=0;i<100;i++){
System.out.println(sl_Name);
}
}
This is valid
#2) int il_Count=0;
.
.
.
synchronized(il_Count){
}
This is not valid as the variable il_Count is not an object but a primitive data type while in the previous case, sl_Name was a String object that was derived from java.lang.object
Regards,
Ganp.
 
Marcela Blei
Ranch Hand
Posts: 477
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ganapathi:
String is a reference type not a primitive type that�s why you can synchronized it.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!