Can i start a thread in a catch in JAVA - java

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

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.

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. When to catch java.lang.Error?

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).

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.

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.

Related

catching exception and error

We have a piece of code for reading from queue
while(true){
try {
message = readMessageFromQueue();
processMesage(message); //Writes into DB and some other operation
}catch(Exception e) {
log the exception
}
}
Now there are ten threads which are spawned using executor service with the aim of running forever. However we have noticed after sometime we deploy(it can be 10-15 days or month) the number of thread is getting reduced(Write per second is also decreasing because of that).
The question is should we catch Error or only exception in the code which we want to run forever like this and is catching Exception can cause this problem ?
Yes, it's better to catch a Throwable there, not just Exception. Depending on your processing you might get, for example, a StackOverflowError that will kill your thread without logging. You might not be able to recover from it, but at least you can debug the problem latter.
From what I understand, you're asking if it is okay to catch by general Exception versus specific exceptions, like ArrayOutOfBoundsException. So, I guess my answer come down to whatever you prefer. You can catch by Exception, which isn't usually advised because you should always know what your code is doing and thus what could go wrong, but it does accomplish your tasks. Now, the reason you should catch by specific exceptions is that you can have different methods of handling different errors. Maybe the way you are handling the error isn't universally applicable to all errors, so when the thread sees an exception it isn't designed to expect, it crashes leaving you with one less thread.
I prefer catching specific exceptions of I can do something gracefully with that failure (like retry or do some default behavior). But if an exception means the program can't continue at all regardless, than catching the most generic exception and terminating is fine.
catching Exception is a "shotgun" approach to exception handling - "Whatever exception you will throw, I will catch it!".
catching a specific, ideally custom Exception is preferred mainly because you know where that exception is thrown, and you can gracefully handle that exception, or do some methods specifically for a certain exception. Therefore gives you more control of your application.
hope this helps.

Error handling at a higher level

I have try/catch blocks at lower levels to handle most errors, but I was told we need one near the top, basically as a catch all to allow the program to continue operating correctly if there is an error. I put a try/catch(Exception e)/finally around everything at the top level, but we are still getting exceptions causing crashes. I've been looking at the stack trace for any clues... It starts like this (I can post more of it if that would help):
111858 [SimpleAsyncTaskExecutor-2] DEBUG o.h.e.jdbc.spi.SqlExceptionHelper - could not execute statement [n/a]
java.sql.SQLIntegrityConstraintViolationException: ORA-01400: cannot insert NULL into ("DATABASE"."TABLE"."COLUMN")
The weird thing is that the rest of the stack trace never goes back to anything that is ours. It's all oracle/apache/hibernate/springframework until it ends up with:
at java.lang.Thread.run(Thread.java:795) [na:1.7.0]
Any ideas why it's not going back to our code or how better to implement this "catch all"? The finally block is for some steps that we want to implement whether there is an error or not.
Edit: for clarity's sake and because maybe it will help, this is part of a batch that processes files every 5 minutes. The try/catch is like so:
try{
//process file
}catch(Exception e){
//log exception
}finally{
//mark file as processed so it doesn't keep trying to reprocess a broken file
}
You, or a library that you are using must be spawning off a thread somewhere and it is that thread that is throwing the exception.
Your options are
track down the creation of that thread, and handle the exception from there
track down which thread group that the thread belongs to and register an exception handler with that thread group
The best idea I can suggest for implementing this "catch all" is don't do it.
I would, instead, recommend defensive programming at the class level. Each class should handle its own possible exceptions when possible. This will save you time later when something goes wrong and you have to track down where to came from.
You need to debug and find where the thread is being created and handle exceptions there.

Java equivalent to php die

I've done some research to know if there is an equivalent to PHP die in java
Sometimes I'm doing small tests and I really want to stop my code at specific line , and return doesnt stop the code like "die" in php
Is there a die quivalent in java?
Use System.exit(0); to exit the java code.
Keep a note this will stop the JVM instance which is currently running.
If you want to come out of a method use return or throw exception to showcase error condition.
try:
System.out.println(message);
System.exit(0);
Disclaimer: I'm not that familiar with Java, I have a basic working knowledge of it, but haven't done a huge amount of work with it.
I suppose you could just throw() an exception and not catch it, that should halt execution. Of course if you have an exception handler for exceptions that aren't caught locally you might have problems.
Most IDEs let you set breakpoints where execution will stop and you'll be able to examine the state of variables, look at the call stack and so on. Both Eclipse and Netbeans support this. It might be a better option.
EDIT: There is also System.exit() which will halt execution. I still think breakpoints are a better option though.
<% if(true)return; %> ok

Question about Java.lang.Error

There are lot of posts on java.lang.Error saying it should not be caught. My question is if it should not be caugth the what is the use of it. Since it is Throwable so we can catch it in try catch. I read some posts like only in some situation it should be caught, how to know these situations.
In short i want to know what can go wrong when i catch Error. What is process behind it. Why they have made Error and its Subclasses? If my app is not supposed to catch them then what catches them? Why my code cannot handle this caught Error? If i simply catch one Error and write some handling code in Catch block, won't that code run?
An Error (especially a subclass of VirtualMachineError) indicates that the JVM has encountered an internal issue - one that means that its internal state may no longer be consistent. If you catch an Error and attempt to recover, future behaviour is undefined. The reason that errors are Throwable is so they can be thrown - eg you may do it your self for errors in a native library that can't be recovered from (eg the library could have written to JVM memory, or corrupted its internal static state). The same stack walking and stack trace producing machinery is used in the case of all Throwables - it would be silly to have another mechanism to do the same thing.
Most errors in the JVM that are not VirtualMachineErrors are situations where a native library could have corrupted its static state - eg AWTError, ZipError.
However there are some rare cases where catching an Error is sane: AssertionError in a testing framework, and LinkageError where you have to deal with the absence / presence of different versions of libraries at runtime. This is a pretty rare requirement and may be better handled through reflection.
All rules have exceptions (except this one).
Even if everybody say you should not, there are plenty of cases where it's totally appropriate to catch those java.lang.Error. The logic behind the rule was: "do not try to continue running your application after a fatal condition was detected". You therefore must be careful before doing something after such an error is thrown. It is possible that the system might not be able to continue its task afterward.
It might be OK for a servlet to catch OutOfMemoryError, log the error and destroy the session. Maybe the problem was with that precise session. Destroying it would restore the memory and allow other users to continue using the system. However, you should have a mechanism to track those errors in real-time in order to:
Fix programming errors
(AssertionError, StackOverflowError)
Fix configuration errors
(UnsatisfiedLinkError)
Correct JVM sizing parameters (OutOfMemoryError)
This kind of handling should be done very "high" in the call stack (i.e. near the main()), where the main loop (or equivalent) is performed. I think it's not a good practice to catch Error in deep code, you should at least rethrow the error in those cases.
Similar question already answered here - When to catch java.lang.Error?
Basically, you should never attempt to catch it as its thrown on fairly serious issues like when your thread has dead for some reason, and is not recoverable.
There are however sometimes the need to catch the error when dealing with the framework itself as stated in the above URL.

What can cause this Java behaviour?

My project generates some text/binary files. If I run it normally, some files will have a pretty low size ( which indicates something went wrong ). If I run it from debug mode ( stepping through code ), the files will be generated correctly.
What can cause this behaviour? I'm pretty sure I don't have any unclosed files.
EDIT: I've gone through the code in a more focused way, and I've found the problem. At one point in time, the files get compressed, and this explains the decrease in size. I'm stupid :)
A moderator can close this question if he sees fit.
Try adding:
System.gc();
try { Thread.sleep(4000); } catch (Exception e) {}
System.gc();
...at the end of your program. If the problem goes away then you did forget to close() a file. The above code is no solution, it is a hacky attempt to increase the likelyhood finalizers will run.
Is your code multithreaded? Are you trying to read something that you haven't given another thread a chance to finish constructing, which doesn't manifest when you're stepping through it?
Do you call some kind of "read" method, to read from a file, for example, and assume that you will always get back the number of bytes that you request?

Categories

Resources