I am trying to spawn a thread for just 1 method. Im getting an IllegalStateException (see below). What this method does it accept a Connection to a database and the database name, and it will generate XML from it. (That part works I am just trying to make it go faster with a new thread because I have multiple XML files to create.
Thread table = new Thread(new Runnable() {
public void run() {
try {
System.out.println("starting");
tableXml(tableConn, dbName);
System.out.println("ending");
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
table.start();
Exception:
java.lang.IllegalStateException: Current state = RESET, new state = FLUSHED
at java.nio.charset.CharsetEncoder.throwIllegalStateException(CharsetEncoder.java:951)
at java.nio.charset.CharsetEncoder.flush(CharsetEncoder.java:640)
at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:769)
at com.informix.lang.JavaToIfxType.doConversion(JavaToIfxType.java:841)
at com.informix.lang.JavaToIfxType.JavaToIfxChar(JavaToIfxType.java:145)
at com.informix.jdbc.IfxVarChar.toString(IfxVarChar.java:247)
at com.informix.jdbc.IfxResultSet.getString(IfxResultSet.java:742)
at com.informix.jdbc.IfxResultSet.getString(IfxResultSet.java:785)
at org.apache.commons.dbcp.DelegatingResultSet.getString(DelegatingResultSet.java:225)
at com.test.ex.ExportTask$1.run(ExportTask.java:151)
at java.lang.Thread.run(Thread.java:662)
The line of code that is causing the exception is a resultSet.executeQuery();
So the question is: what am I doing wrong?
Thanks for your help, let me know if you need information
It seems that the problem is because your code is not thread safe. Try giving each new thread that is spawned its own connection instead of sharing a reference of a single connection between all threads in your application.
The exception itself has nothing to do with the way you're firing up a new thread. You're "start-thread-call-method" code is just fine.
The exception is CharsetEncoder related. If I were you, I would google for something like IllegalStateException CharsetEncoder and possibly thread safety.
It is important however, that Whatever classes / framework you're using concurrently are thread safe.
Are you sure the main thread doesn't reset/close the connection while the spawned thread tries using it?
If you're in a Java EE environment (or similar, like Spring), the connection is often linked to the current transaction, which is itself linked to the current thread. So when the transaction ends, the connection is given back to the pool of available connections, but your spawned thread is still trying to use it.
Related
I have some method with render() name which includes very difficult logic and I call it so in my code
Future<File> fileFuture = null;
try {
fileFuture = executor.getThreadPoolExecutor()
.submit(() -> render());
return fileFuture.get(10,TimeUnit.SECONDS);
} catch (TimeoutException e) {
fileFuture.cancel(true);
throw new MyTimeOutException(e);
}
}
render() method opens some I/O resources and when job doesn't finish
till timeout I get such error when timeout happens
java.nio.channels.ClosedByInterruptException
I investigated this problem and found that this happens because
I/O resources stay still open and Thread cannot be terminated
till these resources won't be closed.
But isn't any way for avoiding this exception
I just need to stop my async method when timeout happens.
and I also want add that I use Spring boot if there is any solution with
Spring please tell me
This exception ClosedByInterruptException will be thrown when a thread performing a blocking read or write on an InterruptibleChannel, like a FileChannel, it's interrupted.
When you call fileFuture.cancel(true) the boolean flag indicates that if the task is blocked, the thread may be interrupted. So, as the thread is blocked in a read or write operation it throws a ClosedByInterruptException.
If you want to get rid of the ClosedByInterruptException, then you render() method to tackle with ClosedByInterruptException, to end the process gracefully if it's thrown.
So if I have a socket server, I can accept each socket and pass it to a executory
while(true){
Socket conn = socketServ.accept();
Runnable task = new Runnable() {
#Override
public void run() {
try{
server.executor(conn);
} catch(IOException e){
}
}
};
exec1.execute(task);
}
Doing this allows my server to run on my threads and does not block the same thread. Because I also have reference to that socket... called "conn" I can successfully return messages as well.
Now I have an RMI interface, which basically lets me call methods back and forth.
for example if I had this method:
public MusicServerResponseImpl CreatePlayerlist(String Name, UserObjectImpl uo) throws RemoteException {
MusicServerResponseImpl res = new MusicServerResponseImpl();
return res;
}
Which returns a serializable object. My concern is when this message gets called, I think it is going to get called in the main thread of the server, and thus will block that thread and slow down parallelism.
What I think is the solution is to have every single RMI method also create a task for an executor.. to speed up the execution of everything...this issue I am seeing however is unlike the socket where I have an object to send information back to, I am unsure how I would return a response from the RMI method, without somehow having to block the thread.
Does that make sense? Basically I am asking how I can execute in parallel with RMI methods while still being able to return results!
Thanks for the help!
Does that make sense?
No. Concurrent calls are natively supported.
See this documentation page and look for the property named maxConnectionThreads.
You could also have tested your assumptions by, for example, printing the current thread name in your server code, and trying to execute concurrent calls and see what happens.
I'm developing a multithreaded application to make connections to external servers - each on separate threads - and will be blocked until there is input. Each of these extends the Thread class. For the sake of explanation, let's call these "connection threads".
All these connection threads are stored in a concurrent hashmap.
Then, I allow RESTful web services method call to cancel any of the threads. (I'm using Grizzly/Jersey, so each call is a thread on its own.)
I retrieve the specific connection thread (from the hashmap) and call the interrupt() method on it.
So, here is the question, within the connection thread, how do I catch the InterruptedException? (I'd like to do something when the connection thread is stopped by an external RESTful command.)
So, here is the question, within the connection thread, how do I catch
the InterruptedException?
You can not. Since if your thread is blocked on a read I/O operation it can not be interrupted. This is because the interrupt just sets a flag to indicate that the thread has been interrupted. But if your thread has been blocked for I/O it will not see the flag.
The proper way for this is to close the underlying socket (that the thread is blocked to), then catch the exception and propagate it up.
So since your connection threads extend Thread do the following:
#Override
public void interrupt(){
try{
socket.close();
}
finally{
super.interrupt();
}
}
This way it is possible to interrupt a thread blocked on the I/O.
Then in your run method do:
#Override
public void run(){
while(!Thread.currentThread().isInterrupted()){
//Do your work
}
}
So in your case don't try to catch an InterruptedException. You can not interrupt the thread blocked on I/O. Just check if your thread has been interrupted and facilitate the interruption by closing the stream.
When you call Thread.interrupt() on some thread, what happens is that 'interruption' flag is set for that thread. Some methods do check this flag (by Thread.interrupted() or Thread.isInterrupted()) and throw InterruptedException, but usually only methods that can block do that. So there is no guarantee that InterruptedException will ever be thrown in interrupted thread. If you don't call any method that throws InterruptedException, there is no point in catching that exception, since it will not be thrown at all. However you can always check if your thread was interrupted by calling Thread.isInterrupted().
the problem it is with blocking.
Hoverer, try this code, maybe it will help you:
try{
yourObject.read();
}catch(InterruptedException ie){
// interrupted by other thread
}
catch(Exception ex){
// io or some other exception happent
}
your read method, should check if there is available buytes at socket for eg, if there are than read it, othervise go to speel mode. When is sleeping than is available the wake up (InterruptedException) at pur socket read ( whatever read have you) it will be blocked. Some API has a value to max waiting, eg 5 sec 60 sec, if nothing o read than it will be next code executed.
class MyReadingObject
{
public read() throws InterruptedException{
while(shouldIread){
if(socket.available() > 0){
byte[] buff = new byte[socket.avaialble()]
socket.read(buff);
return;
}
else{
Thread.currentThread.sleep(whateverMilliseconds);
}
}
}
}
something like that, but with error handling and some design patterns
Calling interrupt() on a thread doesn't stop it, it just switches on the interrupt flag. It's the responsibility of the code to handle the change in the interrupt status of the thread in consideration and act accordingly. If you are performing a blocking operation in that thread, you are pretty much SOL because your thread is "blocking" on the read. Have a look at the answer which I posted here. So basically, unless you are looping over stuff or periodically checking some flags inside that thread, you have no way of breaking out without closing sockets or stuff like that.
One solution here is to "explicitly" expose the underlying connection object and call close() on it, forcing it to throw some sort of exception, which can be then handled in the threaded code. Something like:
class MyAction extends Thread implements Disposable {
public void doStuff() {
try {
byte[] data = this.connection.readFully();
} catch (InterruptedException e) {
// possibly interrupted by forceful connection close
}
#Override
public void dispose() {
this.connection.close();
}
}
// Elsewhere in code
MyAction action = conMap.get("something");
action.dispose();
Use a try-catch like so:
try {
//code
} catch ( InterruptedException e) {
//interrupted
}
I think that should do the trick, you could also keep a boolean variable on whether to exit, so they would check that variable, if it's true, stop
Hi guys : This question involves threads, clients, Netty, and Ning.
CONTEXT
The Ning library is an Asynchronous HTTP request tool which allows us to build requests, queue them, and handle them asynchronously. It relies on some libraries, such as the JBoss/Netty code pasted below.
PROBLEM
I recently ran across a Thread closing exception which was thrown by this bit of code in the JBoss/Netty ExecutorUtil class.
This class appears to be essentially a utility for ending threads in Netty.
This method was causing a bug in a web client (powered by Ning) that I was using, by the fact that I was attempting to close an HttpClient inside of a handler for that client's response.
Question
What is the significance of the deadlock this block of code is attempting to avoid ? For further details, the class can be seen at this code url.
// Check dead lock.
final Executor currentParent = DeadLockProofWorker.PARENT.get();
if (currentParent != null) {
for (Executor e: executorsCopy) {
if (e == currentParent) {
throw new IllegalStateException(
"An Executor cannot be shut down from the thread " +
"acquired from itself. Please make sure you are " +
"not calling releaseExternalResources() from an " +
"I/O worker thread.");
}
}
}
In netty you are not allowed to shutdown the Executor from within an IO-Thread (as the exception is telling you already ;)), this is because you would have the risk of see a deadlock. If you really want to shutdown the Executor from within a handler you need to do it in a new thread. Something like for example:
public void messageReceived(...) {
// in IO-Thread
new Thread(new Runnable() {
public void run() {
//....shutdown here
}
}).start();
}
I am using the Javamail API connecting to my IMAP server. Everything is working great with the javax.mail.Folder.idle() method. My listener gets called when a new mail comes in. However the problem is idle blocks forever, how do I interrupt it? How do I actually stop the listening without killing my Java program?
I've tried calling Thread.interrupt() on the idle'd thread. Nothing happens. I am running out of ideas.
Performing any operation on that folder (from another thread) will cause idle() method to return immediately. So if you want to forcefully interrupt it, just call close() from a new thread.
If you read the documentation properly, and read the source code, you'll realise that you have to create a new thread for calling .idle().
Allocate that thread to a variable, and whenever you want call the interrupt() on that thread, or just ignore notifications!
If you need to get idle() going again, just rerun the thread!
I created something similar, so you might wanna check it out.
https://github.com/mofirouz/JavaPushMail/blob/master/src/main/java/com/mofirouz/javapushmail/JavaPushMailAccount.java
Good luck
A proper way to abort IDLE command is the following snippet. Note that the Folder instance should be the same as the one used to start idling. I've tested the other solutions proposed on this thread but they didn't work in my case.
IMAPFolder folder = store.getFolder("INBOX");
try {
folder.doOptionalCommand("Abort IDLE error mesage", new IMAPFolder.ProtocolCommand() {
#Override
public Object doCommand(IMAPProtocol p) throws ProtocolException {
p.idleAbort();
return Boolean.TRUE;
}
});
} catch (MessagingException e) {
e.printStackTrace();
}