Search code examples
javahashmapstatic-blockmain-method

Getting Error : Exception in thread "main" while executing program for different loop conditions in static block


There is no problem in program execution if i am having loop condition as little value (i.e. 1000 or 10000) in static block, its working. the problem is in loop in static block for given code. whenever i am executing below code i am getting exception "could not find main class" see the below code :

import java.util.HashMap;
import java.util.Map;
public class TestStatic {
static HashMap<String,Integer> testMap = new HashMap<String,Integer>();

public static void main(String[] args) {
    for (Map.Entry<String,Integer> entry : testMap.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }
   }
 static
  {
    for(int i=0; i< 10000000; i++)
    {
        testMap.put("key_" + i, i);
    }
  }
 }

but whenever i am changing the value of loop condition to 1000000 (with one less number of 0). the code is working fine. so is there any time constraints to execute static block. i know there is size limitation to 64k, but i just want to clarify that, this is happening because of this limitation or any other reason is there behind this.


Solution

  • There is nothing wrong with your code. You are not running into limitations of static blocks. You are simply running out of heap memory. Each key and value in your map is unique and as you add a zero to the end of the loop condition you are creating 10x more of them.

    You can increase the size of the Java heap with the -Xmx switch when you run java. E.g. use -Xmx1024m to give yourself 1Gb heap. Even that may not be enough (I haven't done the calculation!) but you'll soon find out.