package com.blah;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;
import lombok.Value;
@Component
public class AdminCredentialsProvider {
@Value
public class AuthInfo {
String authToken;
String xsrfToken;
}
private AuthInfo adminAuthInfo = null;
private final ScheduledExecutorService adminAuthInfoRefresher =
Executors.newSingleThreadScheduledExecutor();
//This will be called by multiple threads
public AuthInfo getSiteAdminCredentials() {
return new AuthInfo(adminAuthInfo.getAuthToken(), adminAuthInfo.getXsrfToken());
}
@PostConstruct
public void init() {
adminAuthInfo = loginAsSiteAdmin();
Runnable runnable = () -> {
//Do I need to protect this assignment with a lock at all
adminAuthInfo = loginAsSiteAdmin();
};
adminAuthInfoRefresher.scheduleAtFixedRate(runnable, 1, 1, TimeUnit.HOURS);
}
private AuthInfo loginAsSiteAdmin() {
//call rest endpoint to login
return new AuthInfo("mockToken", "mockXsrf");
}
}
adminAuthInfo
variable is only set by one thread (after initial assignment).
The AuthInfo class is immutable
I am aware that the java =
(reference assignment) is atomic.
I know I can implement this with AtomicReference, or ReadWriteLock. But is a lock necessary here at all?