You have not really given enough information and code details for a certain Answer. But I will give it a shot.
AtomicReference
To quote the comment above by scottb:
Thread safety of shared variables is about visibility and atomicity of state transitions.
I often prefer the use of the Atomic… classes to address both visibility and atomicity. These classes can provide an alternative to volatile and synchronized.
In this case, we can use AtomicReference class to hold as its payload a reference to your current desired String value. Notice that we mark it final as the reference to the AtomicReference object itself will never change. Its payload, a reference (pointer) taking us to the desired String object, does change. At one moment it may point to the String value "dog" while a moment later it may point to the String value "cat". But the container of either String is always the very same AtomicReference object, a wrapper around that contained text, that contained String object.
If your InfoTO class looked like this:
package work.basil.example;
public class InfoTO
{
private String nric ;
public String getNric ( ) { return this.nric; }
public void setNric ( String nric ) { this.nric = nric; }
}
…then your DaoImpl might look something like this:
package work.basil.example;
import java.util.concurrent.atomic.AtomicReference;
public class DaoImpl
{
private AtomicReference < String > sNric;
private void setInfo ( InfoTO pers )
{
this.sNric.set( pers.getNric() );
}
public InfoTO getInfo ( )
{
InfoTO pers = new InfoTO();
String s = retrieveDetail();
pers.setNric( s );
return pers ;
}
private String retrieveDetail ( )
{
return this.sNric.get();
}
}
Your lines:
sNric = retrieveDetail();
pers.setNRIC(sNric);
…do not make sense to me. You use a field to hold what is a temporary value. So I substituted a local variable instead.
Your retrieveDetail method makes no sense to me. You seem to be returning from calls to a database the very same string value you are caching in the field sNric. So I changed that method to access the cached field sNric. This seems more consistent with your intended logic, and more importantly, shows both the getter and setter of the AtomicReference in action.
Of course, as others said, you may well have other thread-safety issues in the substantial code you did not show us.