• Post Reply Bookmark Topic Watch Topic
  • New Topic

Objects and Threads  RSS feed

 
Surender Singh
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ALL
I saw following statement in JVMspec :---

Acquiring the lock associated with an object does not of itself prevent other threads from accessing fields of the object or invoking unsynchronized methods on the object. Other threads can also use synchronized methods or the synchronized statement in a conventional manner to achieve mutual exclusion.

Threads Objects 14.8


My views:
if ThreadA acquire a lock on Object A during invoking a synchronized method then another ThreadB can access or reference to Object A can invoke simultaneously Unsynchronized method on ObjectA.
Can any body elaborate more....
[ May 05, 2008: Message edited by: Surender Singh ]
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Surender,

you're assumptions are right! Every thread which doesn't synchronize on any lock can access Object A or its fields. There's no "built-in" synchronization in Java, so the programmer has to take care of properly using locks and other synchronization mechanisms. So it's absolutely legal to access any unsynchronized methods of an object even so another thread may hold the intrinsic lock of the object in question.

It should be noted that this access to Object A from more than one threads of course isn't thread-safe if not ALL accessing threads use proper synchronization but manipulate the same member variables.

Marco
[ May 06, 2008: Message edited by: Marco Ehrentreich ]
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I will try to explain this in non-technical terms:

Assume a house that has 2 rooms, Room A and Room B.
Both the rooms have only one door and are locked. The key to the lock is placed outside the room.
Anyone who wants to enter the room will take the key, open the door get in, lock the door from inside. Finish his work, come out, lock the door and put the key back.
People always have to come in a queue to take the key.

Now, lets assume, there are 4 people in the house. 2 people wants to use room A and the other wants to use room B.

Following the above rules, 2 people can simultaneously access different rooms but not the same one (as the person using the room locks it from inside)
Access to one room is always sequential.

If you apply this analogy to thread, objects and locks.
The house will be an Object instance.
Rooms will be methods.
Locks will be object monitors (i.e. locks)
People will be threads.

Hope it helps.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!