We examined the implementation of exclusive processing (Java) when sharing a timed token for Web API authentication (assuming an OAuth2 access token) among multiple threads.
The specifications for token management assume the following.
The token management class that works with the above specifications is implemented as follows.
public class TokenManager {
//Singleton pattern
private static TokenManager instance = new TokenManager();
private TokenManager() {}
public static TokenManager getInstance() {
return instance;
}
/*Token and update date and time should be volatile variables so that the latest state can always be obtained at the time of reference.*/
//Timed token
private volatile String token = null;
//Update date and time (UNIX time stamp) calculated from the token validity period
private volatile long refreshAt = 0L;
//Synchronized is not required because the latest state is acquired with a volatile variable.
public String getToken() {
if (System.currentTimeMillis() >= refreshAt) {
syncUpdateToken();
}
return this.token;
}
//Update processing is synchronized and exclusively controlled (so that only one thread can be executed at a time)
private synchronized void syncUpdateToken() {
//Do not re-execute the update process in the subsequent thread that called getToken during the update process.
if (System.currentTimeMillis() < refreshAt) {
return;
}
//Token update process
//To ensure that the latest token can be obtained when the expiration date verification is passed by the getToken method.
// token ->Refresh in the order of refreshAt.
this.token = ...
this.refreshAt = ...
}
}
By making the instance variable (token, refreshAt) a volatile variable, it is not necessary to make the token reference method (getToken) synchronized, and the reference processing within the token expiration date can be executed in parallel.
In this case, since the subsequent thread that called getToken during the update process calls the token update method (updateToken), the expiration date is verified again in the method to prevent unnecessary token update process.
Recommended Posts