Reputation: 880
So I have the following scenario (can't share the actual code, but it would be something like this):
public class Test
{
private Object obj;
public void init()
{
service.registerListener(new InnerTest());
}
public void readObj()
{
// read obj here
}
private class InnerTest implements Listener
{
public synchronized void updateObj()
{
Test.this.obj = new Object();
// change the obj
}
}
}
The InnerTest
class is registered as listener in a service. That Service is running in one thread the calls to readObj()
are made from a different thread, hence my question, to ensure consistency of the obj
is it enough to make the UpdateObj()
method synchronized?
Upvotes: 0
Views: 710
Reputation: 19911
I would suggest using another object as a lock to ensure that the class only blocks when the obj
is accessed:
public class Test
{
private final Object lock = new Object();
private Object obj;
public void init()
{
service.registerListener(new InnerTest());
}
public void readObj()
{
synchronized(lock){
// read obj here
}
}
private class InnerTest implements Listener
{
public void updateObj()
{
synchronized(Test.this.lock){
Test.this.obj = new Object();
// change the obj
}
}
}
}
Then use that lock in all methods that need to have consistent access to obj
. In your current example the readObj
and updateObj
methods.
Also as stated in the comments, using synchronized
on the method level in your InnerTest
class, will not really work as you probably intended. That is, because synchronized methods will use a synchronized
block on the this
variable. Which just blocks your InnerTest
class. But not the outer Test
class.
Upvotes: 3