Search code examples
multithreadinghashmaphashsetconcurrentmodification

ConcurrentModificationException in HashSet


I have my code as below and I'm getting ConcurrentModificationException, particularly in the line for (String file : files)

I don't change anything for the "file" when doing iteration, so why the exception will be caused and how should I avoid it? Thanks for any suggestion!

int getTotalLength(final HashSet<String> files) {
        int total = 0;
        int len;
        for (String file : files) {
            len = getLength(file);
            if (len != Long.MIN_VALUE) {
                total += len;
            }
        }
        return total;
    }




      int getLength(String file) {
        int len = Long.MIN_VALUE;

        if (file == null) {
            return len;
        }

        File f = new File(file);

        if (f.exists() && f.isFile()) {
            len = f.length();
        }

        return size;
    }

Solution

  • Refering to you comment, declaring final HashSet<String> files makes variable files finale - that means that you cannot assign another object to this variable inside this variable's scope. HashSet itself is mutable object and can be modified - it has nothing to do with final modifier (reference to the set object itselt is still the same). If you want to work concurently on same object (same hashset) use synchronized blocks or methods.

    Generally speaking, you cannot modify collection (in same or another thread) that are beeing iterated with for loop in for-each alike variant.