How do I make sure each thread is using different unique ID and that ID should be in between startExistingRange and endExistingRange. As I am worried because the program is supposed to run for 60 minutes and before the 60 minutes it is possible that all the id’s would have been used then what should I do. Should I reset the variables? What can be the best practice?
For Example:- Thread 1 will be using 25, Thread 2 will use 45 etc etc.
class ThreadTask implements Runnable {
private int id;
public ThreadTask(int id) {
this.id = id;
}
public void run() {
System.out.println("Thread " + id);
}
}
public class TestPool {
public static void main(String[] args) {
int size = 10;
int durationOfRun = 60;
int startExistingRange = 1;
int endExistingRange = 1000;
// create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(size);
// queue some tasks
long startTime = System.currentTimeMillis();
long endTime = startTime + (durationOfRun*60*1000);
// Running it for 60 minutes
while(System.currentTimeMillis() <= endTime) {
/* I want each thread uses different unique ID between startExistingRange
and endExistingRange */
service.submit(new ThreadTask(What should I pass
here so that each thread is using different ID));
}
// wait for termination
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
}
Updated:-
public class TestingPool {
public static void main(String[] args) throws InterruptedException {
int size = 10;
int durationOfRun = 1;
IdPool idPool = new IdPool();
// create thread pool with given size
ExecutorService service = Executors.newFixedThreadPool(size);
// queue some tasks
long startTime = System.currentTimeMillis();
long endTime = startTime + (durationOfRun * 60 * 1000L);
// Getting and releasing id in while loop
while(System.currentTimeMillis() <= endTime) {
Integer id = idPool.getId();
service.submit(new ThreadTask(idPool, id));
idPool.releaseId(id);
}
// wait for termination
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
}
class IdPool {
private final LinkedList<Integer> availableIds = new LinkedList<Integer>();
public IdPool() {
for (int i = 1; i <= 1000; i++) {
availableIds.add(i);
}
Collections.shuffle(availableIds);
}
public synchronized Integer getId() {
return availableIds.removeFirst();
}
public synchronized void releaseId(Integer id) {
availableIds.add(id);
}
}
class ThreadTask implements Runnable {
private IdPool idPool;
private int kk;
public ThreadTask(IdPool idPool, int s) {
this.idPool = idPool;
this.kk = s;
}
public void run() {
//Integer id = idPool.getId();
System.out.println("Task " + kk);
//idPool.releaseId(id);
}
}
Instead of passing an ID to your task at creation time, have your task get their ID from a pool of available IDs. Since you have 10 threads, you only need 10 IDs. Each task takes an ID from the pool at startup, and releases it to the pool when done. Of course, the pool needs to be thread safe: