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

  • SEARCH
  • Home
  • 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 1867956
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T06:37:34+00:00 2026-05-17T06:37:34+00:00

I was reading about CopyOnWriteArrayList and was wondering how can I demonstrate data race

  • 0

I was reading about CopyOnWriteArrayList and was wondering how can I demonstrate data race in ArrayList class. Basically I’m trying to simulate a situation where ArrayList fails so that it becomes necessary to use CopyOnWriteArrayList. Any suggestions on how to simulate this.

  • 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-17T06:37:35+00:00Added an answer on May 17, 2026 at 6:37 am

    A race is when two (or more) threads try to operate on shared data, and the final output depends on the order the data is accessed (and that order is indeterministic)

    From Wikipedia:

    A race condition or race hazard is a flaw in an electronic system or process whereby the output and/or result of the process is unexpectedly and critically dependent on the sequence or timing of other events. The term originates with the idea of two signals racing each other to influence the output first.

    For example:

    public class Test  {
        private static List<String> list = new CopyOnWriteArrayList<String>();
    
        public static void main(String[] args) throws Exception {
            ExecutorService e = Executors.newFixedThreadPool(5);
            e.execute(new WriterTask());
            e.execute(new WriterTask());
            e.execute(new WriterTask());
            e.execute(new WriterTask());
            e.execute(new WriterTask());
    
            e.awaitTermination(20, TimeUnit.SECONDS);
        }
    
        static class WriterTask implements Runnable {
    
            @Override
            public void run() {
                for (int i = 0; i < 25000; i ++) {
                    list.add("a");
                }
            }
        }
    }
    

    This, however, fails when using ArrayList, with ArrayIndexOutOfbounds. That’s because before insertion the ensureCapacity(..) should be called to make sure the internal array can hold the new data. And here’s what happens:

    • the first thread calls add(..), which in turn calls ensureCapacity(currentSize + 1)
    • before the first thread has actually incremented the size, the 2nd thread also calls ensureCapacity(currentSize + 1).
    • because both have read the initial value of currentSize, the new size of the internal array is currentSize + 1
    • the two threads make the expensive operation to copy the old array into the extended one, with the new size (which cannot hold both additions)
    • Then each of them tries to assign the new element to array[size++]. The first one succeeds, the second one fails, because the internal array has not been expanded properly, due to the rece condition.

    This happens, because two threads have tried to add items at the same time on the same structure, and the addition of one of them has overridden the addition of the other (i.e. the first one was lost)

    Another benefit of CopyOnWriteArrayList

    • multiple threads write to the ArrayList
    • a thread iterates the ArrayList. It will surely get ConcurrentModificationException

    Here’s how to demonstrate it:

    public class Test  {
        private static List<String> list = new ArrayList<String>();
    
        public static void main(String[] args) throws Exception {
            ExecutorService e = Executors.newFixedThreadPool(2);
            e.execute(new WriterTask());
            e.execute(new ReaderTask());
        }
    
        static class ReaderTask implements Runnable {
            @Override
            public void run() {
                while (true) {
                    for (String s : list) {
                        System.out.println(s);
                    }
                }
            }
        }
    
        static class WriterTask implements Runnable {
            @Override
            public void run() {
                while(true) {
                    list.add("a");
                }
            }
        }
    }
    

    If you run this program multiple times, you will often be getting ConcurrentModificationException before you get OutOfMemoryError.

    If you replace it with CopyOnWriteArrayList, you don’t get the exception (but the program is very slow)

    Note that this is just a demonstration – the benefit of CopyOnWriteArrayList is when the number of reads vastly outnumbers the number of writes.

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

Sidebar

Related Questions

While reading about constant interface antipattern, i found final constant class with no instances
After reading about the System.Diagnostics.Contracts.Contract static class that has been influenced by the awesomeness
In reading about C#, I have come across the terms data transfer type and
Reading about the problem of creating a read only primitive vector in C# (basically,
After reading about Mapper XMLs I can't help to wonder how one might go
While reading about wireless technology, I usually meet the term provisioning. Anyone can help
I am reading about HibernateTemplate class in Spring3. Here i saw two methods update
I have been reading about how read.table is not efficient for large data files.
I was reading about this EntityProxy feature in GWT 2.1+ and was wondering if
When reading about SQL Injection and XSS i was wondering if you guys have

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.