0

So, Lets say I have a

  String s = "{(30,2884090,1410450570357,235),(30,2863348,1410451100148,285)}";
  Matcher match = Pattern.compile("(\\d+,)*\\d+").matcher(s);

So the issue is sometimes, the String s is so big that I get heap error:

 java.lang.OutOfMemoryError: Java heap space
 at java.util.Arrays.copyOfRange(Arrays.java:2694)
 at java.lang.String.<init>(String.java:203) 
  1. How do i handle this as an exception, so that my code still keeps on
  2. going Any better way to handle such large strings?
ntalbs
  • 28,700
  • 8
  • 66
  • 83
frazman
  • 32,081
  • 75
  • 184
  • 269
  • Can you split up the string? Why do you need One Jumbo string? – Jay Sep 17 '14 at 23:33
  • 1
    How big is "so big"? – Oliver Charlesworth Sep 17 '14 at 23:34
  • You can't handle it and keep going when you run out of memory. You need to figure out how to avoid it. – khelwood Sep 17 '14 at 23:35
  • 3
    Take a step back. Running out of memory allocating a single string is a big red flag. Whatever it is you're doing with this humongous string, there's got to be a better way to do it. For instance, if you read a huge file's contents into memory, try switching to a streaming approach. – John Kugelman Sep 17 '14 at 23:35
  • 1
    *“How do i handle this as an exception, so that my code still keeps on”* – You can catch an `OutOfMemoryError` just like any other exception but it is not clear what you would do to recover from it so having your application killed is probably the best you can hope for. – 5gon12eder Sep 17 '14 at 23:58
  • You can attempt to catch the OutOfMemoryError. Sometimes you can handle it. (Sometimes there's not enough storage available to even catch the exception.) Since all that storage is internal to the constructor it will go unreferenced as soon as the exception is caught, and so you should have no trouble continuing if you can actually make it to the `catch`. – Hot Licks Sep 18 '14 at 01:13

2 Answers2

1

You can't really handle it as an Exception. You may rather either:

  • Increase the size of the JVM Heap via the XMS/XMX parameters (See here)
  • Use a streaming approach, so not everything is loaded in memory.
Community
  • 1
  • 1
yohm
  • 452
  • 7
  • 14
0

Have a look here, it's a great resource for handling different types of OOM (out of memory) exceptions with strings. It shows how to either use concatenation (easy, but easily throws errors also!) or the StringBuffer (a well optimised solution)

Also, if you need, you can increase the available heap size using the -Xmx command, some helpful hints here

KyleM
  • 508
  • 2
  • 4
  • 11