I have been trying to find out how JVM handles runtime exception in RMI remote methods. I have a remote method that contains the following two methods:
doSomething(
print "doSomething thread id " + Thread.currentThread.getId()
)
fail(){
print "fail thread id " + Thread.currentThread.getId()
throw new RunTimeException
}
The behavior I saw was that even if method fail() is invoked, the thread on which the runtime exception was thrown is still not terminated. A sample output is:
fail thread id 16
stacktrace
...
doSomething thread id 16
doSomething thread id 16
The exception is caught. The caller will get a ServerException with your RuntimeException nested in it as the cause. The executing thread doesn't die.
Related
Context
I have a webservice writing a test id in a queue. Then, a listener reads the queue, searches the test and starts it. During those steps, it writes updates of the test in the database in order to be shown to the user. To be more precise: the test is launched in a docker container and at the end of it, I want to update the status of the test to FINISHED. For that, I use the docker java library with a callback.
Problem
When it comes to call the callback, I receive multiple error messages on the call to update the test (but it happens only once, if I try twice the second time works, but it still writes a lot of error messages from the transaction manager).
Here are the error messages logged:
2020-11-20 09:20:43,639 WARN [docker-java-stream--1032099154] (org.jboss.jca.core.connectionmanager.listener.TxConnectionListener) IJ000305: Connection error occured: org.jboss.jca.core.connectionmanager.listener.TxConnectionListener#600268e6[state=NORMAL managed connection=org.jboss.jca.adapters.jdbc.local.LocalManagedConnection#236f1a69 connection handles=1 lastReturned=1605860423264 lastValidated=1605860242146 lastCheckedOut=1605860443564 trackByTx=true pool=org.jboss.jca.core.connectionmanager.pool.strategy.OnePool#2efb0d3b mcp=SemaphoreConcurrentLinkedQueueManagedConnectionPool#3e8e7a62[pool=ApplicationDS] xaResource=LocalXAResourceImpl#482fdad2[connectionListener=600268e6 connectionManager=4c83f895 warned=false currentXid=null productName=Oracle productVersion=Oracle Database 18c Enterprise Edition Release 18.0.0.0.0 - Production
Version 18.3.0.0.0 jndiName=java:/ApplicationDS] txSync=TransactionSynchronization#1387480544{tx=Local transaction (delegate=TransactionImple < ac, BasicAction: 0:ffffac110002:-50a6b0bf:5fb6bdb9:73db4 status: ActionStatus.ABORTING >, owner=Local transaction context for provider JBoss JTA transaction provider) wasTrackByTx=true enlisted=true cancel=false}]: java.sql.SQLRecoverableException: IO Error: Socket read interrupted
2020-11-20 09:20:43,647 INFO [docker-java-stream--1032099154] (org.jboss.jca.core.connectionmanager.listener.TxConnectionListener) IJ000302: Unregistered handle that was not registered: org.jboss.jca.adapters.jdbc.jdk8.WrappedConnectionJDK8#4f3c1cb2 for managed connection: org.jboss.jca.adapters.jdbc.local.LocalManagedConnection#236f1a69
2020-11-20 09:20:43,656 WARN [docker-java-stream--1032099154] (com.arjuna.ats.jta) ARJUNA016031: XAOnePhaseResource.rollback for < formatId=131077, gtrid_length=29, bqual_length=36, tx_uid=0:ffffac110002:-50a6b0bf:5fb6bdb9:73db4, node_name=1, branch_uid=0:ffffac110002:-50a6b0bf:5fb6bdb9:73db8, subordinatenodename=null, eis_name=java:/ApplicationDS > failed with exception: org.jboss.jca.core.spi.transaction.local.LocalXAException: IJ001160: Could not rollback local transaction
Caused by: org.jboss.jca.core.spi.transaction.local.LocalResourceException: IO Error: Socket read interrupted
at org.jboss.ironjacamar.jdbcadapters#1.4.22.Final//org.jboss.jca.adapters.jdbc.local.LocalManagedConnection.rollback(LocalManagedConnection.java:139)
...
Caused by: java.sql.SQLRecoverableException: IO Error: Socket read interrupted
at com.oracle.jdbc//oracle.jdbc.driver.T4CConnection.doRollback(T4CConnection.java:1140)
...
Caused by: java.io.InterruptedIOException: Socket read interrupted
at com.oracle.jdbc//oracle.net.nt.TimeoutSocketChannel.handleInterrupt(TimeoutSocketChannel.java:258)
...
Explanation
At the beginning, I thought about a connection problem, maybe the the transaction is no more available at the callback time (because the docker run took too long), maybe it has to be invalidated.
But at the end, as written in the console, it came from an interruption of the thread when it tries to acquire the lock to update the test and I discovered where this interruption came from: I took a look at the method executeAndStream in DefaultInvocationBuilder from the docker java library and I discovered this:
Thread thread = new Thread(() -> {
Thread streamingThread = Thread.currentThread();
try (DockerHttpClient.Response response = execute(request)) {
callback.onStart(() -> {
streamingThread.interrupt();
response.close();
});
sourceConsumer.accept(response);
callback.onComplete();
} catch (Exception e) {
callback.onError(e);
}
}, "docker-java-stream-" + Objects.hashCode(request));
thread.setDaemon(true);
thread.start();
And here it is, the closable given to onStart interrupts the thread. After that, I discovered in the method onComplete from ResultCallbackTemplate (that I was extending for my callback) a close on that closable:
#Override
public void onComplete() {
try {
close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Resolution
The problem finally came from the following code I wrote:
#Override
public void onComplete() {
super.onComplete();
updateTest(FINISHED);
}
I was calling the onComplete method from the parent without knowing what is does and as usual, first before doing anything else. To correct that, I only had to call the super method at the end:
#Override
public void onComplete() {
updateTest(FINISHED);
super.onComplete();
}
I'm learning Java threads tutorial and can't understand the explanation of last question 'Threads and exceptions':
Now suppose we run this test:
#Test public void testThreadOops() {
new Thread(() -> { throw new Error("thread oops"); }).start();
}
Is a stack trace for Error: thread oops printed? ( ) Yes ( ) No
The test: ( ) Passes ( ) Fails
The explanation for this question is:
The Error occurs on the newly-created thread, terminating that thread with a stack trace on the console. But the test method testThreadOops returns normally – there is no exception on the main thread – and the JUnit test passes. It does not detect the oops.
Why is there no exception in the main thread?
Is a stack trace for Error: thread oops printed?
It depends.
An uncaught exception on a child thread (i.e. not the "main" thread) will be passed to the thread's uncaught exception handler, the threadgroup uncaught exception handler, or the default uncaught exception handler. These would typically be responsible for printing a stacktrace.
If you (or your framework) don't set a handler, the default behavior is to do nothing, and there won't be a stacktace anywhere.
(The methods for setting handlers are described in the javadocs for Thread.)
Why is there no exception in the main thread?
Because the exception is not thrown on the main thread. It is thrown ... and must be caught / handled ... on the child thread's stack.
Think of it this way. If an exception on a child thread was somehow rethrown on the parent thread, where would you catch it? How would you deal with it? What if it was a checked exception, and the context didn't allow that particular exception to be thrown?
There is no exception thrown in the main thread simply because this code doesn't throw an exception in the main thread. It starts a new thread, and throws an exception in that new thread - not in the main thread.
When an exception is thrown (and not caught) in a thread, that thread terminates, but it doesn't "pass" the exception back to the "parent" thread that started it in the first place. If that happened, any thread which started other threads would continuously be at risk of stopping at any time because of an exception thrown in one of its "child" threads. If the "parent" thread were stopped half-way through some computation, it could leave some data in an invalid state.
In the method below you are throwing an exception in the new thread you create not the main thread of the application. So no exception is thrown in the main thread.
new Thread(() -> { throw new Error("thread oops"); }).start();
Normally when an exception occurs in a thread it terminates itself instead of passing the exception in the main thread. This is to protect the main(parent thread) from stopping incase of child thread cause an exception.
I am getting below exception ONLY when high load is running like 25 calls (same scenario) per second and it is not coming for every call, it is coming for few times only.However, when I run few calls at a time i am not getting this exception. I checked that method public execute method exists in com.abc.block.Rules class and this is the reason exception is not coming when i run few calls.
02 Oct 2019 02:00:01,021 [Worker[23]] ERROR [SNode] 80]
NoSuchMethodException during reflective call on class
com.abc.block.Rules java.lang.NoSuchMethodException:
com.abc.block.Rules.execute(com.abc.common.cdata) at
java.lang.Class.getMethod(Class.java:1786)
While running load reflection is not working correctly. Any inputs please ?
Code :
Object port = service.getClass()
.getMethod(xmlSNode.getPortMethodName()).invoke(service);
outResult = port
.getClass()
.getMethod(xmlSNode.getOperation().getName(),
inputs.getInputTypes())
.invoke(port, data);
Rule call :
public Object[] execute(cdata c) throws Exception{
...
}
Any input please
While reading jvm specification I came across exception (2.10 Exceptions)
Most exceptions occur synchronously as a result of an action by the
thread in which they occur. An asynchronous exception, by contrast,
can potentially occur at any point in the execution of a program ...
What are the differences between the two types ?
Keeping reading, the specification gives and example of an asynchronous exception
An asynchronous exception occurred because: – The stop method of class
Thread or ThreadGroup was invoked, or – An internal error occurred in
the Java Virtual Machine implementation.
But what makes stop method of a class thread special in this regard ?
Can you explain the differences between the two and give some examples of them, other than the given ones ?
The stop method can be called from another thread which could leave the data altered by the thread stopped in an inconsistent state.
For this reason Thread.stop() is being removed. I suggest you not use it.
Can you explain the differences between the two and give some examples of them, other than the given ones
The difference is that an asynchronous exception is triggered by another thread at any point in the code.
They should not happen under normal operation.
A specific implementation of the JVM could have other errors but there is not exhaustive list.
There isn't much you can do about except shutdown gracefully.
Here's an example showing the two types of exception. Consider the following code snippets, which show the two kinds of exception being raised, and handled:
public static void main(String[] args) throws Exception {
try {
syncException();
} catch (RuntimeException re) {
System.out.println("-1-");
re.printStackTrace();
}
CompletableFuture<Void> f = null;
try {
f = asyncException();
} catch (RuntimeException ex) {
System.out.println("-2-" + Thread.currentThread().getName());
ex.printStackTrace();
}
try {
f.get();
} catch (Exception ex) {
System.out.println("-3-");
ex.printStackTrace();
}
}
A synchronous exception
private static void syncException() {
throw new RuntimeException("Sync exception #" + Thread.currentThread().getName());
}
And an asynchronous exception - raised in a different thread from the calling code:
private static CompletableFuture<Void> asyncException() {
return CompletableFuture.runAsync(() -> {
throw new RuntimeException("Async exception #" + Thread.currentThread().getName());
}, Executors.newFixedThreadPool(1));
}
Now, when that code is executed, the following stack traces are produced:
The synchronous exception's stack trace:
-1-
java.lang.RuntimeException: Sync exception #main
at stackoverflow.Main.syncException(Main.java:34)
at stackoverflow.Main.main(Main.java:11)
Note that -2- was not printed, because the exception was asynchronous. See the third catch block's stack trace for how asynchronous exceptions are handled. Note that the thread in which the exception was raised is different from the one printing the stack trace:
-3-
java.util.concurrent.ExecutionException: java.lang.RuntimeException: Async exception #pool-1-thread-1
at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895)
at stackoverflow.Main.main(Main.java:26)
Caused by: java.lang.RuntimeException: Async exception #pool-1-thread-1
at stackoverflow.Main.lambda$0(Main.java:39)
at java.util.concurrent.CompletableFuture$AsyncRun.run(CompletableFuture.java:1626)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
An asynchronous exception, by contrast, can potentially occur at any point in the execution of a program ...
Just a comment on this: you'll notice that the code in thread pool-1-thread-1 could raise the exception any time of the main thread's execution. This is probably relative among threads. But in this example, the main thread being the main programe execution, we can say that the "Async exception #pool-1-thread-1" exception occurred asynchronously.
I have a task scheduler implemented in my application. Basically, what i do is schedule some task's to be executed 4 times in a day (like 6 in 6 hours), so the system schedules it to: 00:00, 06:00, 12:00, 18:00.
Ok, i have a class (FlowJobController) which extends the Thread class and in the run() implementation i keep sleeping the thread in 60 to 60 seconds, so it's executed again to check if there's any task to be executed. If true, i run my Job.
Basically the main part it:
rSet = pStmt.executeQuery();
while (rSet.next()) {
long jobId = rSet.getLong("trf_codigo");
String ruleName = rSet.getString("reg_nome");
String ruleParameters = rSet.getString("trf_regra_parametros");
Job job = new Job();
job.setId(jobId);
job.setRuleName(ruleName);
job.setParameters(Functions.stringToList(ruleParameters, "\n"));
FlowJob flowJob = new FlowJob(this, job);
flowJob.start();
}
} catch (Exception ex) {
logger.error(WFRSystem.DEFAULT_USER, system.getCode(), ex);
} finally {
try {
DBConnection.close(pStmt);
DBConnection.close(rSet);
// executede 60 in 60 sec
Thread.sleep(60 * 1000);
} catch (InterruptedException ex) {
logger.error(WFRSystem.DEFAULT_USER, system.getCode(), ex);
}
}
The thing is: When the pStmt.executeQUery() returns records to be executed, it goes into the while and the error appears into the line: Job job = new Job();
The error is:
Exception in thread "FlowJobController" java.lang.NoClassDefFoundError: wfr/com/Job
at wfr.com.FlowJobController.run(FlowJobController.java:112)
Before this error i got this error:
25/09/2012 12:00:09 org.apache.catalina.loader.WebappClassLoader loadClass
INFO: Illegal access: this web application instance has been stopped already. Could not load wfr.com.Job.
The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact.
java.lang.IllegalStateException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1566)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at wfr.com.FlowJobController.run(FlowJobController.java:112)
The FlowJobController.java:112 is the Job job = new Job();
What am i doing wrong?
The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact.
If you are saying that your code deliberately threw the IllegalStateException exception, then that is the likely cause of the subsequent problems. If you throw an uncheck exception in static initialization, and that exception propagates, then the class initialization fails, and the class (and all classes that depend on it) are unusable. In this case, it looks like it also caused the webapp to be stopped.
If this is the problem, the solution is "don't do that". Fix whatever is causing the exception to be thrown.
The other possibility is that this is simply a missing class problem:
Well, that sounds not possible (to not be in the war) since i'm running into the eclipse environment and it's in the class folder directory and no errors is shown about not finding those classes...
The class loader won't be looking in the Eclipse classes folder. It will be looking in the webapp directory on your web container (Tomcat, Jetty, whatever).