javaexceptionhuffman-codeconcurrentmodification

ConcurrentModificationException logic breakdown


As per docs ConcurrentModificationException states: ConcurrentModificationException occurs when an object is tried to be modified concurrently when it is not permissible.

I'm trying to de-rust on some java conceptsand make a huffman compression application.
I have a helper function that I believe is causing this, but I am unsure why.

When I pass in root and set it to the new root which is returned by huffmanHelper

(my code probably isn't doing fully what I want it to yet)
My question: * behind the scenes why is what I am attempting a problem in java.*

thank you

package huffman;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Scanner;

public class huffman {

public static Map<Character, Integer> frequency = new HashMap<Character, Integer>();
public static PriorityQueue<node> nodesPQ = new PriorityQueue<node>();

public static void main(String[] args) {
    
    /* get input */
    Scanner scanner = new Scanner(System.in);
    String input = scanner.nextLine();
    frequency = inputFrequency(frequency,input);
    System.out.println(frequency);
    scanner.close();
    nodesPQ = createNodes(nodesPQ, frequency);
    node a = nodesPQ.poll();
    node b = nodesPQ.poll();
    node OGroot = new node(a,b,a.getFrequency() + b.getFrequency(),null);
    node finalRoot = createBranch(nodesPQ,OGroot);
    finalRoot.inorderPrint();
}


/* counts occurrences of letters in output returns Map<Char, # of occurrences> */
public static Map<Character,Integer> inputFrequency(Map<Character,Integer> map,String input){
    /* split input into char Array */
    char[] charsArray = input.toCharArray();
    
    /* fill hashmap ['Char', # of occurrences] */
    for(char i : charsArray) {
        int count = 0;                                                          
        for(char j : charsArray){
            if(i == j) {
             count++;            
            }
            map.put(i,count);                   
        }
    }
    return map;
}


/* take Map of <Character, # of occurrences> and create nodes inside PQ*/
public static PriorityQueue<node> createNodes(PriorityQueue<node> nodePQ,Map<Character,Integer> map){
            
        nodePQ = new PriorityQueue<>();  
        // create nodes inside PQ
        for (Map.Entry<Character,Integer> i : frequency.entrySet())  {
            Character character = i.getKey();
            Integer occurrences = i.getValue();
            node n = new node(null,null,occurrences,character);
            
                nodePQ.add(n);
            }        
      
        return nodePQ;
        } 


 



public static node createBranch(PriorityQueue<node> nodePQ, node root){
    node newRoot = null;
    for(node i : nodePQ) {
        node nextFrequent = nodePQ.poll();
        root = huffmanHelper(nodesPQ,root,nextFrequent);

    }
        return newRoot;
        
}
    





public static node huffmanHelper(PriorityQueue<node> nodePQ, node root, node nextFrequent){
    node newRoot = new node(nextFrequent,root,root.getFrequency() + nextFrequent.getFrequency(),null);
    
    //get next letter and frequency 
    return newRoot; 
        }   
}

my stack trace:

hello my name is sam
{ =4, a=2, s=2, e=2, h=1, y=1, i=1, l=2, m=3, n=1, o=1}
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.PriorityQueue$Itr.next(PriorityQueue.java:536)
    at huffman.huffman.createBranch(huffman.java:83) - is the start of 
    forLoop in createBranch
    at huffman.huffman.main(huffman.java:26) - is node finalRoot = 
    createBranch(nodesPQ,OGroot); in main

Solution

  • This line removes an element from the priority queue:

        node nextFrequent = nodePQ.poll();
    

    It happens inside a loop iterating over the same priority queue, so counts as a forbidden concurrent modification. This causes your exception.

    is there a better way you can think of iterating over a PriorityQueue to remove items? just a regular for loop w PQ.size() ?

    If you want to exhaust the queue in priority order, keep taking out elements until poll() returns null (code is not tested):

        node nextFrequent = nodePQ.poll();
        while (nextFrequent != null) {
            // Do something with nextFrequent
            nextFrequent = nodePQ.poll();
        }
    

    The poll method Retrieves and removes the head of this queue, or returns null if this queue is empty.

    Documentation link: Queue.poll()