I'm calling a method which involves lots of fetching and updating tables that might take 10+ minutes. This is done using a background thread so that the UI is responsive and the user doesn't have to wait for it to complete.
There are chances that an exception might be raised. In that case, I need to udpate the status of a column from "Pending" to "Failed".
Is it fine to do this in the catch block? Can I write a code in the catch block such that a query is executed to update the status to failed? Is this the right way or are there any other ways to do this?
Edit: Can I do something like this, so that when an exception is thrown, the status gets updated to "Failed" and the exception stack trace is printed out?
catch (Exception e) {
updateStatusByReqId(reqKey, "F");
e.printStackTrace();
}
Will this ensure that if there are any exceptions, the status of the request gets changed to "Failed"? Note that on creating the request online, the request will be having the status "Pending". It should remain pending if everything is fine, otherwise changed to "Failed"
If you write the code to update the status in the catch block it will work fine, however since you are inside a method maybe could be better return a boolean value from the methos and update the ui from the caller of the thread, something like this :
private boolean updateDatabase() {
try {
//Your long updating code ...
} catch {
return false;
}
return true;
}
Then you can call the method from the background thread and, log the status in the UI if it return false :
if(!updateDatabase()) {
//Update UI status
}
Doing in this way it is a better style, from my point of view ...
I wouldn't put the code in the catch block. Put the logic to for updating the status (on the GUI?) in a separate class and method and call it:
String currentColumn = "";
try {
// ...
} catch (SomeExceptions se) {
updateColumnStatus(currentColumn, se); // local method / KISS
continue; // we're in a loop, right?
}
It is fine to write error related code in catch block!
It looks like the exception is some kind of 'normal' busing flow (like validation). So, short answer is you can do some processing in catch block.
Caution: While you can write almost any thing in catch block, prefer to do error handling or error recovery in catch blocks.
What happens the exception was related to database access? You would not able to update the
column to 'failed'. You anyway need to have some additional processing in this case. Why not use the same in all cases?
Related
I have about 30 instances running and submitting data to dynamo, but in my logs, I'm getting a ton of ConditionalCheckFailedException failure messages. The weird thing is, I'm not saving with any conditional check, unless I'm missing something:
private void save(DynamoObject myObject) {
try {
mapper.save(model);
} catch (ConditionalCheckFailedException e) {
// metrics and logging
} catch (Exception e) {
// metrics and logging
}
What could be causing this?
It looks like you are using DynamoDBMapper and specifically #DynamoDBVersionAttribute somewhere and your put item failure is related to the mapper's optimistic locking strategy. The item version on the server is different to that on the client side because of another write to that item, so DynamoDB rejects the put.
You'll need to reconcile the item differences client-side and re-submit.
I have a service, and I would like it to have the following behavior:
If service receives InterruptedException, or JVM shuts down, it should try to stop gracefully
If there's some "catastrophic" event, the service should just quit
Any other exception should be logged, state should reset, and loop should keep running
Loop should not quit under any other circumstance.
So here's a overly simplified version of what I came up with.
On class level:
private static volatile boolean keepRunning = true;
static {
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
keepRunning = false;
}
});
}
And then the loop:
while(keepRunning) {
try {
// Do something useful
Thread.sleep(10000); // just an example of something that can cause InterruptedException
}
catch(InterruptedException e) {
keepRunning = false;
}
catch(Exception e) { // catches all exceptions, but not any errors
// log it
// reset state
}
}
if(!keepRunning) {
// shut down gracefully
}
It seems satisfies all 4 conditions, but there are some problems and unclear parts:
(problem) Catching Exception and not doing anything is against all good practices. But is it acceptable in this case, or there's a better solution?
(question) Is not catching Error all I need to do to satisfy condition #2? Or are there other situations I should be aware of?
(unclear) Usually it's recommended that the "shut down gracefully" code goes into finally section after exception, and I don't really like that I have to check it after loop (if(!keepRunning)). But it seems doesn't fit in finally in this case. Is there a better way to do that?
(question) This code is written for Java 7. Would anything be changed/improved with Java 8?
I will appreciate either direct answers to my questions, or pointers to different patterns/solutions. Thanks in advance.
It is ok to catch the Exception in your case.
Not catching Error is a good practice if you run tests.
The finally block is what you should use to shut down gracefully and yes - the if statement in the finally block is needed and generally ok.
If an error occurs, your finally block will still execute so it is all good.
This code is ok for both Java 7 and Java 8
As the title suggested, I have some code wrapped in a while(true) infinite loop, and all of them are fully caught by try and catch block. This thread is started in the main method, however, after long run, this worker thread is vanished mysteriously when I check using the jstack and causing work accumulated.
Below is my code:
public void run() {
while (true) {
try {
// Consumer consumes from Kafka server
Global.KAFKA_METRIC_DATA_CONSUMER.consume(topic, handler);
} catch (Exception e) {
logger.error("Kafka consumer process was interrupted by exception!");
} finally {
try {
// Prevent restart too often
Thread.sleep(30 * BaseConst.SECOND);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
For my understanding, this structure will keep the thread running so is the consumer. Even if the consume() methods failed, it will restart infinitely. However, as I mentioned above, the whole thread disappear silently without any error log. Could anyone provide some clue please?
Some more information that might be helpful:
I have checked the consume method will never shutdown the consumer
nor close the socket to the server. It will continuously try to
connect server after fail.
I analysed the java heap dump, and I found there is a memory leak
somewhere else in the project, causing memory occupation extremely
high and the gc very often. However, the main method is still
running.
OutOfMemoryError is not an Exception. It's an Error derived from Throwable.
If that was thrown somewhere in your consume(topic, handler), finally would still be called, delaying the inevitable some 30s... but after that the error would be passed upward and your loop would be terminated.
You are catching Exception so there's a chance that a java.lang.Error or a java.lang.Throwable is being thrown (eg OutOfMemoryError)
If you really want to catch everything, you'll need to catch Throwable and not just Exception subclasses.
Your thread is probably killed by an error.
An error is not an exception! But they both extend Throwable
Add another catch block that catches errors.
Throwable should never be caught, because errors require a different handling than exceptions
We're calling "lock()" on a ReentrantLock and threads are getting stuck there when they apparently shouldn't.
When debugging with a breakpoint just before the call to "lock()", the first thread would stop there with the program pointer going to "Thread.exit()".
The lock object's toString() says "unlocked" and it's "state" attribute is "0".
The behavior is not always the same. Sometimes the first thread goes past the lock as expected.
userLock.lock(); //first thread sometimes gets stuck here (and the following ones as well)
//"userLock" has "state=0" and toString() says "UNLOCKED"
try {
Transaction tr = HibernateConfig.getSessionFactory().getCurrentSession().beginTransaction();
try {
execute();
tr.commit();
} catch (ConstraintViolationException e) {
//probably traces with repeated time
System.err.println(e.getMessage());
if (tr.isActive()) {
tr.rollback();
}
} catch (RuntimeException e) {
e.printStackTrace();
if (tr.isActive()) {
tr.rollback();
}
}
} catch (Throwable e) {
e.printStackTrace();
} finally {
userLock.unlock();
}
try to put a breakpoint after userLock.lock(); then you should get the thread, that gets the lock.
alternatively you could use userLock.getOwner(); right behind .lock() to see wich thread got the lock.
The problem was my breakpoint was not before "lock()" like I said, but on it.
What happened is a bunch of threads would be blocked in that line by the breakpoint, one of them would still acquire the lock, and then the debugger would give me control over a random one of them which hadn't acquired the lock. And I was failing to check every thread blocked by the breakpoint to find the free one.
In the end I put the breakpoint actually before the lock and it behaved as expected.
This was confusing and I hope the question will still help someone.
Note: I'm still confused by the fact the lock's state said "unlocked" in the debugger while I was controlling a locked thread.
Sometimes, you just have to catch Throwable, e.g. when writing a dispatcher queue that dispatches generic items and needs to recover from any errors (said dispatcher logs all caught exceptions, but silently, and then execution is continued on other items).
One best practice I can think of is to always rethrow the exception if it's InterruptedException, because this means someone interrupted my thread and wants to kill it.
Another suggestion (that came from a comment, not an answer) is to always rethrow ThreadDeath
Any other best practices?
Probably the most important one is, never swallow a checked exception. By this I mean don't do this:
try {
...
} catch (IOException e) {
}
unless that's what you intend. Sometimes people swallow checked exceptions because they don't know what to do with them or don't want to (or can't) pollute their interface with "throws Exception" clauses.
If you don't know what to do with it, do this:
try {
...
} catch (IOException e) {
throw new RuntimeException(e);
}
The other one that springs to mind is to make sure you deal with exceptions. Reading a file should look something like this:
FileInputStream in = null;
try {
in = new FileInputStream(new File("..."));;
// do stuff
} catch (IOException e) {
// deal with it appropriately
} finally {
if (in != null) try { in.close(); } catch (IOException e) { /* swallow this one */ }
}
Depends on what you are working on.
if you are developing an API to be used by some one else, its better to re-throw the Exception or wrap it into a custom exception of yours and throw.
Whereas if you are developing an enduser application you need to handle this exception and do the needful.
What about OutOfMemoryError (or perhaps its super class VirtualMachineError)? I can't imagine there is much you can do after something that serious.
If you're writing a dispatcher queue, then by the time the exception comes back to you there's no point in doing anything with it other than logging it. The Swing event queue has basically that type of behavior.
Alternatively, you could provide a hook for an "uncaught exception handler," similar to ThreadGroup. Be aware that the handler could take a long time, and end up delaying your dispatcher.
As far as InterruptedException goes: the only thing that cares about that is your dispatch loop, which should be checking some external state to see if it should stop processing.