views:

129

answers:

5

I am trying to solve the collatz conjecture.

I am using HashMap and Vector classes. I have to iterate the loop 2 147 483 648 times, but after I store 8,438,409 values in HashMap I'm getting an OutOfMemoryError.

I'm running the program in Eclipse and have set -Xmx1024m option, but it didn't help. So, I'm catching the above error and trying to start a thread which would take the control to different class and start executing.

However, the thread is not starting. I've put System.out.println("We are here"); statement in it and it's never printed to the console. Can someone help me with this?

Thanks funny

+4  A: 

Yes you can start a thread in a catch block.

However, you probably won't be able to start a thread if you're getting an OutOfMemoryError. OutOfMemoryError means you're running out of heap space, and all threads use the same heap space (and in fact, creating a new thread will use up some of your already diminished heap).

Laurence Gonsalves
+8  A: 

You have stumbled onto the difference between an exception and an error in java. Both errors and exceptions descend from throwable but just catching an exception will not catch an error. However errors are usually pretty serious and are difficult if not impossible to recover from see. http://stackoverflow.com/questions/352780/when-to-catch-java-lang-error

stimms
+12  A: 

You don't want to start a thread in your catch {} block. That's trying (and failing) to treat the symptoms while ignoring the cause entirely.

What you want to do is stop that OutOfMemory error from occurring. Your options are to increase the heap size, or use less of it.

Anon.
I must say, Well put.
Frank V
A: 

Yes,

there is no restriction on starting a thread in a catch block. However, the nomal behavior when capturing an exception is show it to users, logging, throw another exception instead, close your application.

As said for the others, in your case you're trying to catch a java.lang.Error, which is not an Exception, and you don't have guarante of the next line of code execution.

nandokakimoto
+1  A: 

You shouldn't need to iterate over every value to solve a question based on the collatz conjecture. I'd assume you are trying to calculate each value. This is an approach that I tried but ran in to the same thing (though, I was using .net).

Rather than trying to solve the technical problem, I'd like to suggest that you alter your approach.

Note: I realized, I assumed (with no cause), that you are trying to solve a ProjectEuler.net question (or the alike). If this is not the case, my solution may not be viable.

Frank V