Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

To which of the following can we apply the synchronized keyword

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To which of the following can we apply the synchronized keyword
Options :
a . A top level class
b . A static member variable
c . A static method
d . An instance variable
e . An instance method
I think the answer is c, d, e,
You can apply the „synchronized“ to an instance method
class Blair2 extends Thread {
public synchronized void run() {

You can apply the „synchronized“ to an instance variable like „t“:
class Blair extends Thread {
public void run() {
Thread t = Thread.currentThread();
synchronized (t) {

Appreciate your oppinion.
Thanks.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Threads.
 
Ken Krebs
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot apply synchronized to a variable. You can only apply it to a method or a code block. If you apply it to a static method, any thread must acquire the class's object lock before it may continue executing the synchronized code. If you apply it to an instance method, any thread must acquire the instance's object lock before it may continue executing the synchronized code. If you apply it to a block of code, any thread must acquire the specified object's lock to continue executing the synchronized code.
Ken Krebs
"The way of the threaded warrior is resolute acceptance of thread death." --- Ken Krebs with apologies to Miyamoto Musashi
 
Greg Charles
Sheriff
Posts: 2993
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This may just be a semantic dispute, but when you synchronize a block of code, you do apply "synchronized" to an object. Of course, it's the block of code you are synchronizing, not the object itself. Synchronizing an object has no meaning.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic