I run the code below for 60 minutes, and what it does is that each thread will use different unique identifiers, regardless of whether the command was previous or not. If it has a value of "Previous", then it will use an existing identifier between 1 and 1000, and if it is not "Previous", it will use a unique identifier between 5000 and 10000. I wrote this code in which the command "Team" has "Previous", then each thread will use a unique Identifier between 1 and 1000, and if it was not previously, it will use a unique identifier between 5000 and 10000.
So, the task statement looks like this: If the command has the previous one, then each thread will use a unique identifier between 1 and 1000. And if it is not the Previous one, then each thread will use a unique identifier between 5000 and 10000
My question is 1) Is this the right way to do this? Or what could be the best way 2) Secondly, it is really very slow. Sometimes it stops, and it does not use a unique identifier between these numbers. and I need to reuse the id if id is complete
class IdPool {
private final LinkedList<Integer> availableExistingIds = new LinkedList<Integer>();
private final LinkedList<Integer> availableNewIds = new LinkedList<Integer>();
public IdPool() {
for (int i = 1; i <= 1000; i++) {
availableExistingIds.add(i);
}
for (int k = 5000; k <=10000; k++) {
availableNewIds.add(k);
}
}
public synchronized Integer getNewId() {
return availableNewIds.removeFirst();
}
public synchronized void releaseNewId(Integer id) {
availableNewIds.add(id);
}
public synchronized Integer getExistingId() {
return availableExistingIds.removeFirst();
}
public synchronized void releaseExistingId(Integer id) {
availableExistingIds.add(id);
}
}
class ThreadNewTask implements Runnable {
private IdPool idPool;
private Command command;
public ThreadNewTask(IdPool idPool, Command cmd) {
this.idPool = idPool;
this.command = cmd;
}
public void run() {
if(command.getDataCriteria().equals("Previous")) {
Integer id = idPool.getExistingId();
newMethod(id);
idPool.releaseExistingId(id);
} else {
Integer newId = idPool.getNewId();
newMethod(newId);
idPool.releaseExistingId(newId);
}
}
private void newMethod(Integer i) {
System.out.println("Task ID: " +i);
}
}
public class TestingPool {
public static void main(String[] args) throws InterruptedException {
int size = 10;
int durationOfRun = 60;
IdPool idPool = new IdPool();
ExecutorService service = Executors.newFixedThreadPool(size);
long startTime = System.currentTimeMillis();
long endTime = startTime + (durationOfRun * 60 * 1000L);
while(System.currentTimeMillis() <= endTime) {
Command nextCommand = getNextCommandToExecute();
service.submit(new ThreadNewTask(idPool, nextCommand));
}
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
}
source
share