Solved

URL openStream Timeout Error

Posted on 2001-06-29
17
14,080 Views
Last Modified: 2011-08-18
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
Comment
Question by:Nivlesh
  • 7
  • 5
  • 3
  • +2
17 Comments
 
LVL 2

Accepted Solution

by:
Prasanna_Hebbar earned 100 total points
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
If you open the connection using a Socket instead of URLConnection then you can set your timeout on the Socket object.
0
 
LVL 2

Expert Comment

by:Prasanna_Hebbar
Comment Utility
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
 
LVL 8

Author Comment

by:Nivlesh
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 3

Expert Comment

by:jerelw
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
But if the thread is blocked (waiting for connection) then it'll never check for exit condition.
0
 
LVL 8

Author Comment

by:Nivlesh
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 2

Expert Comment

by:Prasanna_Hebbar
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 2

Expert Comment

by:Prasanna_Hebbar
Comment Utility
objects, you are right. For blocked IO calls, join does not work.
0
 
LVL 2

Expert Comment

by:Prasanna_Hebbar
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
How does that stop a BLOCKED thread?
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 
LVL 8

Author Comment

by:Nivlesh
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
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
 

Expert Comment

by:Mediestunt
Comment Utility
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This video teaches viewers about errors in exception handling.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now