JVM-Java Virtual Machine will limit your execution with some space of memory if you exceed the allocated memory you got to experience this "JAVA HEAP SPACE"
ERROR.
You can also increase the Heap space by doing this,
java -Xms<initial heap size> -Xmx<maximum heap size> CLASS_FILE_TO_EXECUTE
-Xms<size> set initial Java heap size
-Xmx<size> set maximum Java heap size
Ie
java -Xmx2g
assign 2 gigabytes
of ram as maximum to your app
But you should see if you don't have a memory leak first.