Filling a queue asynchronously via a thread

I was working with a hardware random number generator (RNG) and what it came down to was we needed a cache of numbers that were available, but also needed the fill the numbers without slowing the process of giving out numbers. I settled on storing the data in a queue. I used a blocking queue to prevent the consumers from ever getting the same number.

private Queue<Integer> values = new LinkedBlockingQueue<>();

When a number was pulled off the queue, I also started a thread that would ensure that the queue was never empty.

    public int nextInt(int min, int max) {
        FillQueue fillQueue = new FillQueue();;

        return values.poll();

The thread that filled the queue was an inner-class.

     * Thread used to fill the queue asynchronously.
    private class FillQueue extends Thread {

         * When an object implementing interface <code>Runnable</code> is used to create a thread, starting the thread
         * causes the object's <code>run</code> method to be called in that separately executing thread.
         * <p/>
         * The general contract of the method <code>run</code> is that it may take any action whatsoever.
         * @see Thread#run()
        public void run() {
            if (values.size() < MIN_QUEUE_LENGTH) {
                try {
          "Retrieving {} integers from Comscire", START_QUEUE_LENGTH - MIN_QUEUE_LENGTH);
                    getIntegersFromConscireProcess(START_QUEUE_LENGTH - MIN_QUEUE_LENGTH);
                } catch (IOException e) {
                    logger.error("Unable to add integers to queue by thread", e);
This entry was posted in Java and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s