3

I need to get an access token from a server lazily, so I have this code:

object MyObj {
    val accessToken: String by lazy { getAccessTokenFromHttpApi(username, password) }
}

This works well and is thread-safe, which is a requirement as I get the access token from multiple threads.

Now I learn that this server gives out access tokens that expire after an hour. If the application has been running for more than an hour, the access token will be rejected. When that happens, it needs to be refreshed using another call to getAccessToken...(). However, I can't refresh the value of accessToken as it's a val, which is immutable. How can I refresh while still keeping it thread-safe?

k314159
  • 5,051
  • 10
  • 32
  • If it needs to change, it's not a `val`, it's a `var`. You need to handle your thread-safe elsewhere or in a different manner. Delegate this to a function that is thread-safe, that checks if it's null, then fetches. If it's not null then it checks if it's expired, etc. – Martin Marconcini Sep 14 '21 at 13:32

1 Answers1

0

Val is not immutable it is read only! Here is simple example to give you an idea how you can solve this

class AcessToken(var t : String){
    val token: String
        get() = this.t
}
val token = AcessToken("asd")
println(token.token) //asd

//refresh should be executed as synchronized
synchronized(token){
    token.t = "dsa"        
}
println(token.token) //dsa
Vojin Purić
  • 2,140
  • 7
  • 9
  • 22