Вопрос

After taking help from StackOverflow, I found the solution that I have implemented below.

Problem Statement:-

Each thread needs to use UNIQUE ID every time and it has to run for 60 minutes or more, So in that 60 minutes it is possible that all the ID's will get finished so I need to reuse those ID's again. So I am using ArrayBlockingQueue concept here.

Two Scenario:-

  1. If the command.getDataCriteria() contains Previous then each thread always needs to use UNIQUE ID between 1 and 1000 and release it for reusing again.
  2. Else if the command.getDataCriteria() contains New then each thread always needs to use UNIQUE ID between 2000 and 3000 and release it for reusing again.

Question:-

One weird thing that I have just noticed is- In the below else if loop if you see my below 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)) {

Below is my code:-

class ThreadNewTask implements Runnable {
      private Command command;
      private BlockingQueue<Integer> existPool;
      private BlockingQueue<Integer> newPool;
      private int existId;
      private int newId;


      public ThreadNewTask(Command command, BlockingQueue<Integer> pool1, BlockingQueue<Integer> pool2) {
            this.command = command;
            this.existPool = pool1;
            this.newPool = pool2;
      }

      public void run() {

            if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_PREVIOUS)) {
                  try {
                        existId = existPool.take();
                        someMethod(existId);
                  } catch (Exception e) {
                        System.out.println(e);
                  } finally {
                        existPool.offer(existId);
                  }
            } else if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_NEW)) {
                  try {
                        newId = newPool.take();
                        someMethod(newId);
                  } catch (Exception e) {
                        System.out.println(e);
                  } finally {
                        newPool.offer(newId);
                  }
            }
      }

      // And this method needs to be synchronized or not?
      private synchronized void someMethod(int i) {
            System.out.println();
            System.out.println("#####################");
            System.out.println("Task ID: " +i);
            System.out.println("#####################");
            System.out.println();
      }
}

public class TestingPool {
      public static void main(String[] args) throws InterruptedException {
            int size = 10;
            int durationOfRun = 60;
            LinkedList<Integer> availableExistingIds = new LinkedList<Integer>();
            LinkedList<Integer> availableNewIds = new LinkedList<Integer>();
            for (int i = 1; i <= 1000; i++) {
                  availableExistingIds.add(i);
            }
            for (int i = 2000; i <= 3000; i++) {
                  availableNewIds.add(i);
            }
            BlockingQueue<Integer> existIdPool = new ArrayBlockingQueue<Integer>(1000, false, availableExistingIds);
            BlockingQueue<Integer> newIdPool = new ArrayBlockingQueue<Integer>(1000, false, availableNewIds);

            // create thread pool with given size
            ExecutorService service = new ThreadPoolExecutor(size, size, 500L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10), 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) {
                  Command nextCommand = getNextCommandToExecute();
                  service.submit(new ThreadNewTask(nextCommand, existIdPool, newIdPool));
            }

            // wait for termination        
            service.shutdown();
            service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); 
      }
}

Update:-

One weird thing that I have just noticed is- In the below else if loop if the command is Previous then also it gets entered in the else if block which shouldn't be happening right? Why this is happening? I have no clue why this thing is happening?

else if(command.getDataCriteria().equals(PDSLnPConstants.DATA_CRITERIA_NEW)) {
Это было полезно?

Решение

There is no way if you enter an if () that you enter the else as well so something else is happening. I don't see anything wrong with your code so I suspect that you are misinterpreting your output. Are you expecting a different Command to come from getNextCommandToExecute()?

I just ran your code with a simulated Command which sets a random dataCriteria and got the following output. I see nothing wrong with it:

Task ID: 2001
Task ID: 1
Task ID: 2002
Task ID: 2003
Task ID: 2
Task ID: 2004
Task ID: 3
Task ID: 2005
...

Are you expecting some sort of specific timing for your threads? Given thread race conditions, the first Command produced is not necessarily the first output you will see.

Here is some general feedback on your code:

  • I would use pool.put(...) instead of offer(...) which could return false.
  • You might as well fill your queues after you construct them as opposed to loading them with a LinkedList.
  • You should use ArrayList instead of LinkedList usually.
  • You load in for (int i = 2000; i <= 3000; i++) but that needs to be from 2001 to 3000 else it will be more than 1000 numbers.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top