I've been trying to learn more about thread safety and have been trying to think of good practices when implementing thread safe code. In the context of token retrieval, I want to keep track of the current time, and the time the token will expire (divided in half, so I will refresh in advance of the token expiring). Here's some pseudo code on the situation I'm thinking about
long renewTime = 0; //should this be a volatile long?
Lock lock = new Lock
Service someService = new Service();
public void authenticateWithSomeService() {
try {
lock.get()
//...call to login with someService
renewTime = System.currentTimeMillis() + someService.getToken.getExpirationTime/2
catch (Exception e) {
//log or rethrow
} finally {
lock.unlock();
}
}
private void refreshToken() {
if(System.currentTimeMillis() > renewTime) {
//...call to renew token with someService
long newTime = someService.getToken.getExpirationTime/2
renewTime = System.currentTimeMillis() + newTime;
}
}
public synchronized String getStuff() {
refreshToken(); //check if token needs to be refreshed
try {
//...some HTTP call to get an item with the service
} catch (Exception e) {
//log or rethrow
}
}
So in a scenario like this, are we guarenteed that renewTime
will only ever be read/written by one thread at a time since 1. the authentication method employs locks and 2. the getStuff
method which read and writes renewTime
is synchronized? Is this threadsafe or does renewTime
need to be volatile to ensure the threads access the same value?