Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8434989
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T06:48:33+00:00 2026-06-10T06:48:33+00:00

ExecutorService service = new ThreadPoolExecutor(10, 10, 1000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(10, true), new ThreadPoolExecutor.CallerRunsPolicy()); Problem

  • 0
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)) {
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T06:48:35+00:00Added an answer on June 10, 2026 at 6:48 am

    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:

    id = idPool.getExistingId();
    

    will fail with a NoSuchElementException. In this case, the finally block will run:

    idPool.releaseExistingId(id);
    

    But id will still have its default value of 0 since the first line failed. So you end up “releasing” 0 and adding it back to the id pool even though it was never in the pool to start with. Then a later task could take 0 legitimately.

    However, this should certainly print your exception in the catch block were it happening.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Problem Statement is:- Each thread uses unique ID between 1 and 1000 and program
I'm trying to create a ThreadPoolExecutor: // Thingy implements Delayed and Runnable ExecutorService executor
Does the ExecutorService guarantee thread safety ? I'll be submitting jobs from different threads
My code snippet: ExecutorService executor = Executors.newSingleThreadExecutor(); try { Task t = new Task(response,inputToPass,pTypes,unit.getInstance(),methodName,unit.getUnitKey());
I created multiple ExecutorService instances in my code, usually each UI page has one
my service layer methods are transactional, when i use ExecutorService and submit task to
Suppose I have an ExecutorService (which can be a thread pool, so there's concurrency
I fail to understand why this code won't compile ExecutorService executor = new ScheduledThreadPoolExecutor(threads);
I have a single thread pool ExecutorService object. At some time in the future
Is there a way to use ExecutorService to pause/resume a specific thread? private static

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.