• Post Reply Bookmark Topic Watch Topic
  • New Topic

Lock on Inner class object  RSS feed

 
James Clarke
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Is the following lock on the inner object legal ? It is meant to achieve the following:
The purpose of this inner object lock is to enable the administrator to editUser() or deleteUser() even if someone is doing an addUser().

Does acquiring the lock on the inner object require that we also acquire the lock on the outer object ?

class Outer{

class Inner{
synchronised(Inner.this) addUser(){
// some code to add user
}
}

synchronised(this) editUser(){
// code to edit user
}

synchronised(this) deleteUser(){
// code to delete user
}

}

thanks,

J.C
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happened when you tried it? (I mean, except of the compile time error because of the typo in synchronized... )

Moving to Threads and Synchronization...
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
>Is the following lock on the inner object legal?

Your syntax is off. Write synchronized methods in the normal way, even if it is an inner class:


> It is meant to achieve the following: The purpose of this inner object lock is to enable the administrator to editUser() or deleteUser() even if someone is doing an addUser().

You synchronize on objects, not methods. For example, suppose two threads want to change name fields on the same user object. One wants to change the first name to "George" and the surname to "Washington"; the other to "Abraham" and "Lincoln". Synchronization could prevent the object from ending up with the name "George Lincoln".

If you are introducing an inner class because you think it facilitates synchronization, I think you need to rethink what you are doing.

> Does acquiring the lock on the inner object require that we also acquire the lock on the outer object ?

No, but be careful, because inner methods often access fields in the enclosing object or call methods from the enclosing class.


Perhaps you should state what you are trying to do, because your questions are too low level for any good advice. Your wording actually sounds like you are accessing a database which is a whole 'nother kettle of fish.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!