Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 14260
  • Last Modified:

URL openStream Timeout Error

I am writing an application that will connect to a site and either post or get data from that site. Now sometimes when the network is slow, either from my side or because there is too much load on the server that I am connecting to, my program hangs and keeps hanging. Thus I have to kill the process and restart it... this is really not what I want to be doing since I want this program to be automatic and able to run with the least human intervention. Below is the code that I am using

try{
         in = new BufferedReader(new InputStreamReader(new URL(response_url).openStream()));
     }catch(Exception e2){
         System.out.println("Unable to open inputstream to response url:"+e2);
     }


do{
         try{
          line = in.readLine();
          if (line != null){
              delivery_line += line + "\n";
              if (line.indexOf("success") != -1){
               sms_sent_success = true;
               line = null;
              }
          }
         }catch (Exception e3){
          System.out.println("Error reading from response site:"+e3);
          line = null;
         }
     }while (line != null);

I have traced the problem and it happens when I try to create the bufferedReader.
Is there a way by which I could specify timeout values for the connections to the sites? In that way when the connection is not established within say nsecs then I would get an exception and I could process it.

Help please...
0
Nivlesh
Asked:
Nivlesh
  • 7
  • 5
  • 3
  • +2
1 Solution
 
Prasanna_HebbarCommented:
I am not sure whether there is a way of specifying the timeout value. But you can achieve the same result by opening the url and reading the data in a different thread and starting that thread from the main thread. If the secondary thread does not finish in a specified time period, then you can handle it in a different way.
0
 
objectsCommented:
If you open the connection using a Socket instead of URLConnection then you can set your timeout on the Socket object.
0
 
Prasanna_HebbarCommented:
objects, If I use sockets, then I need to filter out all the http header information which I get from the server. So it involves a lot of coding. Because if you use sockets, you will be dealing with tcp/ip protocol, instead of http protocol. Am I right? I guess usage of thread is a better alternatvie to this.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
NivleshAuthor Commented:
The Usage of Threads where the main thread spawns a child thread which does the I/O with the server and waits a specified amount of time. If the child does not finish then it kills it and spawns another child to do the task.. and this goes on.. ofcourse there will be a delay between respawns so that if there was some load on the server.. it might not be there when we reconnect.

The above was an idea that I had used before but I wanted something that was inbuilt to java.URL I will keep this question open for 5 more days. If there is no better solution than the threads one then Prasanna you will get the points.
0
 
objectsCommented:
Not sure how you'd kill the thread though (w/out using deprecated method). Cause I don't think you can interrupt a blocked IO call.
The only way I can think of to implement what you want is to write your own http protocol handler which would allow you full control over the timeout.
Sorry couldn't be more help :(
0
 
jerelwCommented:
Have one thread read urls

Use a class to call the "Thread"

If the the thread is not complete after a certain time, make the Thread = null;

public class URLReader {

  public static void main(String[] args){
    Vector container = new Vector()
    Thread cnnThread = new URLReader("http://www.cnn.com");
    Thread foxThread = new URLReader("http://www.fox.com");
    cnnThread.start();
    foxThread.start();
    container.addElement(cnnThread);    
    container.addElement(foxThread);    
    Timer t = new Timer(120); //seconds
    boolean done = false;
    while(!done){
      for(int i=0;i<container.size();i++) {
        URLReader t = (URLReader)container.elementAt(i);
        if(!t.complete())
          //wait
        else {
          if(t.getException != null)
          //process          
        }
        if(t.timeOut()) {
          //break;
        }
      }
    }
  }

}
0
 
objectsCommented:
But if the thread is blocked (waiting for connection) then it'll never check for exit condition.
0
 
NivleshAuthor Commented:
I happen to like the Thread.stop() method and I guess that is the one that I will be using...even though it is deprecated but I guess there is no roundabout for the situation that I have at hand.
0
 
Prasanna_HebbarCommented:
Instead of stop method, you can use join method of Thread class. Here is the sample for that.

MainClass
{
  main()
  {
    URLReaderThread thread = new URLReaderThread(url);
    thread.start();
    thread.join(2000); //wait for 2 seconds.
    //After 2 seconds, if the thread does not finish its work, it will be interrupted.
  }
}

class URLReaderThread
{
  public void run()
  {
    //Open the url
    //Read the data from the input stream.
  }
}

   
0
 
objectsCommented:
You can use Thread.stop(), just be aware that it is error prone and can cause deadloack. And will probably disappear in future JDK's.

I don't think Thread.join() will help either, as I believe blocked IO calls cannot be interrupted.
0
 
Prasanna_HebbarCommented:
objects, you are right. For blocked IO calls, join does not work.
0
 
Prasanna_HebbarCommented:
Instead of going for stop() method, I would prefer this ugly loop.

for(int i=0; i<count; i++)
{
  if(thread.isAlive() == false) //Thread completed.
    break;
  Thread.sleep(100); //sleep for 100 milli seconds.
}

//I expect that by count*100 milli seconds, the thread should fetch the data from URL. else stop it.
if(thread.isAlive())
  thread = null;

0
 
objectsCommented:
How does that stop a BLOCKED thread?
0
 
objectsCommented:
Have a look at the HTTPClient class, it's a HTTP implementation (similiar to URLConnection) and it supports timeouts.

http://www.innovation.ch/java/HTTPClient/
0
 
NivleshAuthor Commented:
thanks for your help. I guess there is no way else to get around the http timeout problem other than using threads. have implemented it and uptil now things are running smoothly. Thanks again to all those that responded.
0
 
objectsCommented:
There is a way but good luck :)
Still not sure how your going to kill the blocked thread without using a deadlock prone stop().
0
 
MediestuntCommented:
I had a simulair problem. Its very annoying not being able to control the timeout. I dont know if this was added in one of the new jdk, but at least it works in the newest version of java. Hope someone out there find it useful.
int timeout = 2000;
 
URL url = new URL("http://www.myurl.com");
URLConnection connection = url.openConnection();
connection .setConnectTimeout(timeout);
connection .setReadTimeout(timeout );
 
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream());

Open in new window

0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 7
  • 5
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now