I came across the following code snippet:
static private volatile ConfigUserCredentails maintenanceUserCred = null;
static private Object maintenanceUserLock = new Object();
/**
* This method is slower. Recommend use the one from cache.
*
* @return The username/password credentials of the maintenance user.
* @throws IOException
*/
public static ConfigUserCredentails getMaintenanceUserCredentials() throws IOException {
return readCredentialsFromFile(MAINTENANCE_CREDENTIALS_PROPS, Crypt.getDefaultCrypt());
}
/**
*
* @return The username/password credentials of the maintenance user.
* @throws IOException
*/
public static ConfigUserCredentails getMaintenanceUserCredentialsFromCache() throws IOException {
if (maintenanceUserCred != null) {
return maintenanceUserCred;
}
synchronized(maintenanceUserLock) {
if (maintenanceUserCred == null) {
maintenanceUserCred = getMaintenanceUserCredentials();
}
}
return maintenanceUserCred;
}
'getMaintenanceUserCredentials()' just reads the user credentials from file and creates new user object.
My questions are:
- What is the purpose of 'volatile'?
- Why would one need the 'synchronized' block?
Thanks, Rafik