ExecutorService service = new ThreadPoolExecutor(10, 10, 1000L,
TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10, true), new
ThreadPoolExecutor.CallerRunsPolicy());
Problem Statement is:-
Each thread uses unique ID between 1 and 1000 and program has to run for 60 minutes or more, In my run method I was getting id as zero few times when I did (if(id==0)) check and I put the breakpoint under that loop, I don’t know why? As the availableExistingIds has value in the range between 1 and 1000, then I don’t know from where this zero is coming in my id?
class IdPool {
private final LinkedList<Integer> availableExistingIds = new LinkedList<Integer>();
public IdPool() {
for (int i = 1; i <= 1000; i++) {
availableExistingIds.add(i);
}
}
public synchronized Integer getExistingId() {
return availableExistingIds.removeFirst();
}
public synchronized void releaseExistingId(Integer id) {
availableExistingIds.add(id);
}
}
class ThreadNewTask implements Runnable {
private IdPool idPool;
private int id;
public ThreadNewTask(IdPool idPool) {
this.idPool = idPool;
}
public void run() {
try {
id = idPool.getExistingId();
//Anything wrong here?
if(id==0) {
System.out.println("Found Zero");
}
someMethod(id);
} catch (Exception e) {
System.out.println(e);
} finally {
idPool.releaseExistingId(id);
}
}
// This method needs to be synchronized or not?
private synchronized void someMethod(Integer id) {
System.out.println("Task: " +id);
// and do other calcuations whatever you need to do in your program
}
}
Below is the main class from which program is starting-
public class TestingPool {
public static void main(String[] args) throws InterruptedException {
int size = 10;
int durationOfRun = 60;
IdPool idPool = new IdPool();
// create thread pool with given size
ExecutorService service = new ThreadPoolExecutor(size, size, 500L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(size), new ThreadPoolExecutor.CallerRunsPolicy());
// queue some tasks
long startTime = System.currentTimeMillis();
long endTime = startTime + (durationOfRun * 60 * 1000L);
// Running it for 60 minutes
while(System.currentTimeMillis() <= endTime) {
service.submit(new ThreadNewTask(idPool));
}
// wait for termination
service.shutdown();
service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}
}
Update:-
I was thinking to use ArrayBlockingQueue here so that instead of crashing when there are no available ids, it waits for one to become available. Can anyone suggest me how can I use it here?
Code Change after implementation of BlockingQueue.
public void run() {
System.err.println(command.getDataCriteria());
if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_PREVIOUS)) {
try {
System.out.println(command.getDataCriteria());
// Getting existing id from the pool
existId = existPool.take();
attributeGetSetMethod(existId);
} catch (Exception e) {
getLogger().log(LogLevel.ERROR, e.getLocalizedMessage());
} finally {
// And releasing that existing ID for re-use
existPool.offer(existId);
}
}
else if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_NEW)) {
try {
System.out.println(command.getDataCriteria());
// Getting new id from the pool
newId = newPool.take();
attributeGetSetMethod(newId);
} catch (Exception e) {
getLogger().log(LogLevel.ERROR, e.getLocalizedMessage());
} finally {
// And releasing that new ID for re-use
newPool.offer(newId);
}
}
}
One weird thing that I have just noticed is- In the below else if loop if you see my above code in run method if the command.getDataCriteria() is Previous then also it gets entered in the else if block(which is for New) which shouldn’t be happening right as I am doing a .equals check? Why this is happening?
else if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_NEW)) {
One scenario under which you could get id = 0 (besides the possibility of undefined behaviour due to you not using synchronization) is when the id pool is exhausted (empty). When that happens, the line:
will fail with a NoSuchElementException. In this case, the
finallyblock will run:But
idwill still have its default value of0since the first line failed. So you end up “releasing”0and adding it back to the id pool even though it was never in the pool to start with. Then a later task could take0legitimately.However, this should certainly print your exception in the catch block were it happening.