Re: how to make this code thread safer?
On Mon, 19 Jul 2010, www wrote:
public class MyClass
{
private Person tim = new Person("Tim");
private Person tom = new Person("Tom");
public void doThis
{
this.checkSomething();
Insert this here:
Person tim = this.tim;
if(tim != null) //thread "A" is running "doThis()" and tim is not null at this moment
{
... //other code
tim.doA(); //tim is NULL all of sudden, and NPE is
thrown. I think it is due to another thread running checkSomething()
tim.doB();
tim.doC();
}
}
public void checkSomething() //thread "B" is running checkSomething()
{
if(tim.isAbsent())
{
tim = null;
}
if(tom.isAbsent())
{
tom = null;
}
}
}
That change will prevent NullPointerExceptions emanating from doThis. The
point is that by copying the instance field into a local each thread gets
its own copy, which is insulated from suprising effects.
You still have a risk of NullPointerExceptions from checkSomething - what
if a thread enters that while either tim or tom is already null? I assume
your code is actually doing null checks on the variables as well as
calling isAbsent(). You should protect those in the same way as the code
in doThis.
However! None of this will actually make the code threadsafe, probably,
because it would still be possible for A to come in and set tim to null,
then for B to come in and see an old value for tim and do something with
it. To avoid that, i think it's sufficient to declare tim volatile.
tom
--
isn't it about time we had some new label for people interested in
technology who also have an interest in drinking binges, womanising and
occasional bouts of ultra violence? -- D