1

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?

Terry Lam
  • 11
  • 2
  • i would suggest reading up on semaphores and mutex. here is a good article.. https://www.baeldung.com/java-mutex you need to have a lock mechanism, to lock data. such as an array of semaphores. GL.HC; – 1-14x0r Apr 02 '20 at 22:26
  • No, this isn't thread safe. You'd have to add `volatile` at least to `renewTime`. Java requires synchronization on both reads and writes, since you read `renewTime` without any synchronization this isn't safe. – markspace Apr 02 '20 at 23:34
  • Does this answer your question? [Java: Can two threads access the same method safely if the access is read-only](https://stackoverflow.com/questions/45617711/java-can-two-threads-access-the-same-method-safely-if-the-access-is-read-only) – markspace Apr 02 '20 at 23:35
  • Longs are also subject to word tearing if run on a 32 bit machine without synchronizing them. Please read the spec, it'll answer most of your questions. – markspace Apr 02 '20 at 23:37

0 Answers0