Consider I have this piece of Java code
I wonder if there is a lockless mechanism to make the highlighted piece of code atomic. I want to avoid when someone calls fetchSomeThing()
, I am in the middle of BlockX
and fetchSomeThing()
is looking up from new copy of A but old copies of B and C.
public class MyClass
{
private volatile Map a, b, c;
public void refresh()
{
Map a_ = loadA();
Map b_ = loadB();
Map c_ = loadC();
//I want to make the following block atomic
// call it Block X
{
this.a = a_;
this.b = b_;
this.c = c_;
}
}
public String fetchSomeThing()
{
// some joint operations on this.a, this.b and this.c
}
}
The only way I can think of is to separate this into two classes and wrap up the a, b, c in a single object.
But it is extremely cumbersome. Is there a better way?
public class MyShadowClass
{
private Map a, b, c;
public MyShadowClass()
{
init();
}
public void init()
{
Map a_ = loadA();
Map b_ = loadB();
Map c_ = loadC();
this.a = a_;
this.b = b_;
this.c = c_;
}
public String fetchSomeThing()
{
// some joint operations on this.a, this.b and this.c
}
}
public class MyClass
{
private volatile MyShadowClass shadow;
public void refresh()
{
MyShadowClass tempShadow = new MyShadowClass();
shadow = tempShadow;
}
public String fetchSomeThing()
{
return shadow.fetchSomeThing();
}
}