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 6558863
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T13:15:05+00:00 2026-05-25T13:15:05+00:00

UPDATED: I’ve updated the code based on the correct answer below. This works but

  • 0

UPDATED: I’ve updated the code based on the correct answer below. This works but creates a new problem (I will post a new question).

Creating a blocking bounded buffer class using semaphore’s with multiple producers and consumers.

Goal is to use atomic integer as the pointers so I don’t have to synchronize internally. Overflow handling has been corrected to use CAS now.

But this doesn’t work unless I use synchronized around the AtomicInteger pointers (see comment below). Not sure why? Scroll all the way below to see what I mean by “missing entries”…

public class BoundedBuffer<T> {
private static final int BUFFER_SIZE = Short.MAX_VALUE+1;
private AtomicReferenceArray<T> m_buffer = null;
private Semaphore m_full = new Semaphore(BUFFER_SIZE);
private Semaphore m_empty = new Semaphore(0);
private AtomicInteger m_writePointer = new AtomicInteger();
private AtomicInteger m_readPointer = new AtomicInteger();

public BoundedBuffer() {
    m_buffer = new AtomicReferenceArray<T>(BUFFER_SIZE);
}

public static int safeGetAndIncrement(AtomicInteger i) {
    int oldValue = 0, newValue = 0;
    do {
        oldValue = i.get();
        newValue = (oldValue == Short.MAX_VALUE) ? 0 : (oldValue + 1);
    } while (!i.compareAndSet(oldValue, newValue));
    return oldValue;
}

public void add(T data) throws InterruptedException {
    m_full.acquire();
    synchronized (this) { // << Commenting this doesn't work
        // CAS-based overflow handling
        m_buffer.set(safeGetAndIncrement(m_writePointer),data);
    }
    m_empty.release();
}

public T get() throws InterruptedException {
    T data = null;
    m_empty.acquire();
    synchronized (this) { // << Commenting this doesn't work
        // CAS-based overflow handling
        data = m_buffer.get(safeGetAndIncrement(m_readPointer));
    }
    m_full.release();
    return data;
}
}

Test program has…

8 producer threads, each putting about 10000 entries into the queue.
Each entry is a string of the format: A”:”B
where
A is numbers 0..7 for the 8 threads.
B is just a numerically increasing count from 0..9999

4 consumer threads, consuming everything, until null is hit.

Once producer threads have completed adding everything into the buffer, 4 null’s are added to the queue (to stop the consumers).

Output of the threads…

P:Data, 1:9654@1
P:Data, 5:1097@347
C:Data, 1:9654@1
P:Data, 4:5538@1
C:Data, 4:5538@1
C:Data, null@14466

Verification
When verifying if all entries that were produced were consumer, a few appear missing (just before the arrayindexoutofbounds is hit (may just be a coincidence).

Verifying…
Missing 4:5537
Missing 5:1096
Verified

  • 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-05-25T13:15:06+00:00Added an answer on May 25, 2026 at 1:15 pm

    You need to handle overflows when incrementing the counter. For example, you can use the following method instead of getAndIncrement():

    public static int safeGetAndIncrement(AtomicInteger i) {
        int oldValue = 0;
        do {
            oldValue = i.get();
            int newValue = (oldValue == MAX_VALUE) ? 0 : (oldValue + 1);
        } while (!i.compareAndSet(oldValue, newValue));
        return oldValue;
    }
    

    It uses the typical compare-and-swap approach and shouldn’t harm performance since getAndIncrement() is internally implemented in the same way.

    Also, if MAX_VALUE is BUFFER_SIZE you don’t need % BUFFER_SIZE operation.

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

Sidebar

Related Questions

UPDATED I used below solutions (loading Image from stream), but get new problem. img
Updated Will this line of code work: boost::shared_array<struct sockaddr> addr( reinterpret_cast<struct sockaddr *>( (ipv6
Updated question, see below I'm starting a new project and I would like to
UPDATED See post #3 below. There is a need to upload a file to
Updated below . The following is the entire code I have in my main.cpp:
Updated This is kind of an interesting problem I am experiencing. I need to
Updated code snipped as asked: int MovieNum=children.size(); String[] MovieName=new String[MovieNum]; String[] MovieCover=new String[MovieNum]; RadioGroup
Updated: This may be an easy or a complex question, but in wpf, I
Updated: This question contains an error which makes the benchmark meaningless. I will attempt
[Updated]: Answer inline below question I have an inspecting program and one objective is

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.