Let say I have a class named Home.
public class Home{
public Home() {}
public int getColor() {...)
public int getSize() {...}
public setColor(...) {...}
public setSize(...) {...}
}
(The actual code is irrelevant)
If a method is called from that class by a thread, I would like to cut
the possibility of another thread calling this method or any other
methods of the same instance of this class until the execution of that
method is completed.
An example:
Given a single instance of Home as home.
Thread 1 calls home.getSize();
Thread 2 calls home.getColor(); but since Thread1 is already calling a
method of class home (same instance), it is awaiting until Thread1
finishes using home.
Thread 1 finishes with home.getSize();
Thread 2 can now enter home.getColor();
>From what I understand putting synchronized into
public synchronized int GetColor() {...}
would only work on that method but any other method in home could be
called even if GetColor is already being used.
Is there a simple way to allow only one access to any method of an
instance of a class at the same time?
Thanks for any input.
Gordon Beaton - 28 Dec 2006 07:50 GMT
> From what I understand putting synchronized into
>
[quoted text clipped - 5 lines]
> Is there a simple way to allow only one access to any method of an
> instance of a class at the same time?
Declare *all* of them synchronized.
/gordon

Signature
[ don't email me support questions or followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e
Sundar - 28 Dec 2006 08:44 GMT
Hi Pershing,
I agree with gordon. The following code will work as you expected.
public class Home{
public Home() {}
public synchronized int getColor() {...)
public synchronized int getSize() {...}
public synchronized setColor(...) {...}
public synchronized setSize(...) {...}
}
-Sundar
> > From what I understand putting synchronized into
>
[quoted text clipped - 11 lines]
> [ don't email me support questions or followups ]
> g o r d o n + n e w s @ b a l d e r 1 3 . s e
Sundar - 28 Dec 2006 08:46 GMT
The following tutorial will be helpful in understanding
synchronization.
http://java.sun.com/docs/books/tutorial/essential/concurrency/syncmeth.html
-Sundar
> Let say I have a class named Home.
>
[quoted text clipped - 37 lines]
>
> Thanks for any input.
pershing - 30 Dec 2006 04:21 GMT
Thanks to you all!
> The following tutorial will be helpful in understanding
> synchronization.
[quoted text clipped - 43 lines]
> >
> > Thanks for any input.