I want to create a java application where we want to make vacationers for several users using an access token. I use 1 thread for each user. The access token that I use is valid for 1 hour. After the expiration, I get error 401 and should update the token for all threads and continue. I am thinking about using a mutable variable that I made static to update all threads. My requirement is the moment when I find out in one of the flows that the token has expired, I want all the threads to stop processing and wait until a new token is generated (this takes a couple of seconds). the token should be updated automatically, without failure of each stream due to the expired token.
The following is an example of the code I wrote:
import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class Sample { public static void main(String[] args) { String[] myStrings = { "User1" , "User2" , "User3" }; ScheduledExecutorService scheduledExecutorService = Executors .newScheduledThreadPool(myStrings.length); TokenGenerator.getToken(); for(String str : myStrings){ scheduledExecutorService.scheduleAtFixedRate(new Task(str), 0, 5, TimeUnit.SECONDS); } } } class Task implements Runnable{ private String name; public Task(String name){ this.name = name; } @Override public void run() { getResponse(TokenGenerator.token); } private void getResponse(String token) {
Is there a better approach to this problem? The above code does not satisfy my use case, because as soon as a thread starts generating a new token, all other threads are not suspended. Please suggest some improvements.
java multithreading thread-safety
Anupam
source share