The Artima Developer Community
Sponsored Link

Java Answers Forum
Synchronized statement...

1 reply on 1 page. Most recent reply: Apr 22, 2003 1:29 AM by Alex S

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 1 reply on 1 page
Luka

Posts: 5
Nickname: luka
Registered: Apr, 2003

Synchronized statement... Posted: Apr 21, 2003 11:06 AM
Reply to this message Reply
Advertisement
Dear All,

I hope you might be in a position to help me. As I was studying threads on Bruce Eckel's thinking in java, I came across the synchronized statement.

the following was taken from Java Specs:
"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."

Now, if a method (object B) declares within itself a synchronized statement referencing some other object A , and within the statement calling some methods not synchronized belonging to A, what happens? I mean, what are the monitor regions guarded by the synchronized statement? Isn't it error prone?

I should like to thank you in advance for your help
luka


Alex S

Posts: 27
Nickname: andu
Registered: Mar, 2003

Re: Synchronized statement... Posted: Apr 22, 2003 1:29 AM
Reply to this message Reply
If a thread aquire a lock, any other thread will have to wait if they want to aquire the same lock.

Thread A:

void aMethod(){
synchronized(obj){...}
}

At this moment, let's say thread A has aquired lock on 'obj' object.

Thread B:

void someMethod(){
synchronized(obj){ ... }
}

Thread B is blocked when trying to execute the synchronized block because is wating for thread A to release lock on 'obj' object.

HOWEVER, thread B is allowed to execute something like this while the lock on 'obj' is held by some other thread:

Thread B:

void iDontNeedALock(){
obj.someField = 10;
obj.callAMethod();
...
}

As you can see, even if a thread has aquired a lock on an object, you can do anything you want with that object in other threads as long as you don't try to aquire its lock.

In the end, is up to you to synchronize you code in order to have a bug free code.

Flat View: This topic has 1 reply on 1 page
Topic: can't get server to send file to client Previous Topic   Next Topic Topic: calculate reflection

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use