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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T01:28:24+00:00 2026-05-23T01:28:24+00:00

I am currently trying to learn how to properly handle multi-threaded access to Collections,

  • 0

I am currently trying to learn how to properly handle multi-threaded access to Collections, so I wrote the following Java application.

As you can see, I create a synchronized ArrayList which I try to access once from within a Thread and once without.

I iterate over the ArrayList using a for loop. In order to prevent multiple access on the List at the same time, I wrapped the loop into a synchronized block.

public class ThreadTest {

    Collection<Integer> data    = Collections.synchronizedList(new ArrayList<Integer>());
    final int           MAX     = 999;

    /**
     * Default constructor
     */
    public ThreadTest() {
        initData();
        startThread();
        startCollectionWork();
    }

    private int getRandom() {
        Random randomGenerator = new Random();
        return randomGenerator.nextInt(100);
    }

    private void initData() {
        for (int i = 0; i < MAX; i++) {
            data.add(getRandom());
        }
    }

    private void startCollectionWork() {
        System.out.println("\nStarting to work on data outside of thread");
        synchronized (data) {
            System.out.println("\nEntered synchronized block outside of thread");
            for (int value : data) { // ConcurrentModificationException here!
                if (value % 5 == 1) {
                    System.out.println(value);
                    data.remove(value);
                    data.add(value + 1);
                } else {
                    System.out.println("value % 5 = " + value % 5);
                }
            }
        }
        System.out.println("Done working on data outside of thread");
    }

    private void startThread() {
        Thread thread = new Thread() {
            @Override
            public void run() {
                System.out.println("\nStarting to work on data in a new thread");
                synchronized (data) {
                    System.out.println("\nEntered synchronized block in thread");
                    for (int value : data) { // ConcurrentModificationException
                        if (value % 5 == 1) {
                            System.out.println(value);
                            data.remove(value);
                            data.add(value + 1);
                        } else {
                            System.out.println("value % 5 = " + value % 5);
                        }
                    }
                }
                System.out.println("Done working on data in a new thread");
            }
        };
        thread.start();
    }
}

But everytime one of the for loops gets entered, I get a ConcurrentModificationException. This is my console output (which changes with every new run):

Starting to work on data outside of thread

Entered synchronized block outside of thread
51

Starting to work on data in a new thread

Entered synchronized block in thread
value % 5 = 2
value % 5 = 2
value % 5 = 4
value % 5 = 3
value % 5 = 2
value % 5 = 2
value % 5 = 0
21
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
    at java.util.AbstractList$Itr.next(AbstractList.java:343)
    at ThreadTest.startCollectionWork(ThreadTest.java:50)
    at ThreadTest.<init>(ThreadTest.java:32)
    at MultiThreadingTest.main(MultiThreadingTest.java:18)
Exception in thread "Thread-1" java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
    at java.util.AbstractList$Itr.next(AbstractList.java:343)
    at ThreadTest$1.run(ThreadTest.java:70)

What’s wrong?

Ps: Please don’t just post links to multi-threaded how-to’s since I’ve already read enough about that. I am just curious why my application doesn’t run as I want it to.


Update: I replaced the for(x : y) syntax with an explicit Iterator and a while loop. The problem remains though..

synchronized(data){
        Iterator<Integer> i = data.iterator();
        while (i.hasNext()) {
        int value = i.next(); // ConcurrentModificationException here!
        if (value % 5 == 1) {
            System.out.println(value);
            i.remove();
            data.add(value + 1);
        } else {
            System.out.println("value % 5 = " + value % 5);
        }
    }
}
  • 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-23T01:28:25+00:00Added an answer on May 23, 2026 at 1:28 am

    Once you iterate over a collection, you have a contract between the iterating block of code and the collection as it exists at that moment in time. The contract basically states that you’ll get each item in the collection once, in the order of the iteration.

    The problem is that if you modify the Collection while something is iterating, you cannot maintain that contract. Deletions in a collection will remove the element from the collection, and that element might be required to be present for the initial iteration to satisfy the contract. Insertions in a Collection will likewise present issues if the element might be detected by the iteration that started prior to the element existing in the collection.

    While it is easier to break this contract with multiple threads, you can break the contract with a single thread (if you choose to do so).

    How this is typically implemented is the collection contains a “revision number”, and prior to the iterator grabbing the “next” element in the collection, it checks to see if the collection’s revision number is still the same as it was when the iterator started. This is just one way of implementing it, there are others.

    So, if you want to iterate over something that you might want to change, an appropriate technique is to make a copy of the collection and iterate over that copy. That way you can modify the original collection and yet not alter the count, position, and presence of the items you were planning to process. Yes, there are other techniques, but conceptually they all fall into the “protect the copy you’re iterating across while changing something else that the iterator doesn’t access”.

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

Sidebar

Related Questions

I am currently trying to learn about OpenGL ES for the iPhone and following
I have done a lot with Java but I am currently trying to learn
Greetings, I am currently trying to learn some Java programming. To do this I'm
I am currently trying to learn how to use easymock. I have the following
I'm currently trying to learn OO Javascript so I can write some cleaner code.
I am new to android/java and currently am trying to learn custom events and
I'm currently trying to learn HTML and Java EE Servlet programming. I have an
I'm currently trying to learn game programming, so I'm starting with a simple application
I am currently trying to learn all new features of C#3.0. I have found
I am currently trying to learn C and I have come to a problem

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.