I have used Java applet for developing an application which has the option of uploading of multiple files simultaneously.
Multiple threads are handling the simultaneous upload of files.
When the user clicks on the Cancel button , all the uploads should get cancelled.
I am using HttpMethod for uploading over http connection.
What approach should I follow to close all the instances of http connection at the same time?
I closed the connection manager as follows when the user clicks on the Cancel button to stop all the connections:
manager = new MultiThreadedHttpConnectionManager();
manager.shutdownAll()
But when the user again clicks once again on the Start button , I am trying to create a new instance of connection manager but unable to do so开发者_如何学Go.
I am getting the error
java.lang.IllegalStateException: Connection factory has been shutdown
Also , I tried with the Thread.interrupt() but its not working accordingly i.e. not interrupting all the threads.
Any suggestions/hints will be helpful.
A simple approach would be to interrupt all the upload threads. Your upload runnable should catch InterruptedException
and query a shared cancel flag and cancel the http request.
In the upload worker runnable:
try{
//do http work here
}catch (InterruptedException e){
if(task.isCancelled()){
//cancel http upload
}
}
In the controlling thread
public void onCancel(){
setCancelled(true);
for(UploadWorker uploadWorker: uploadWorkers){
uploadWorker.interrupt();
}
}
Just close and disconnect them. Threads that are blocked in a read() will throw an IOException or possibly a SocketException, so you must code to cope with that.
If thread A is blocked inside a socket, you should be able have another thread (I'll call it 'B') close that socket and unblock 'A'. I don't recall exactly how this works in HttpClient but it uses sockets under the hood so it should still apply.
A single thread 'B' should be able unblock all the sockets sequentially. This is likely overkill but if there's a concern that something could get stuck in close(), you can spawn a separate thread for each blocked socket.
精彩评论