Solved

URL openStream Timeout Error

Posted on 2001-06-29
17
14,122 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
ID: 6240209
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
ID: 6240354
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
ID: 6242570
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
Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

 
LVL 8

Author Comment

by:Nivlesh
ID: 6243217
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
ID: 6243371
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
ID: 6250062
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
ID: 6250793
But if the thread is blocked (waiting for connection) then it'll never check for exit condition.
0
 
LVL 8

Author Comment

by:Nivlesh
ID: 6251052
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
 
LVL 2

Expert Comment

by:Prasanna_Hebbar
ID: 6251328
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
ID: 6251364
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
ID: 6251415
objects, you are right. For blocked IO calls, join does not work.
0
 
LVL 2

Expert Comment

by:Prasanna_Hebbar
ID: 6251429
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
ID: 6251526
How does that stop a BLOCKED thread?
0
 
LVL 92

Expert Comment

by:objects
ID: 6263727
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
ID: 6304114
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
ID: 6304167
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
ID: 21298989
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

Gigs: Get Your Project Delivered by an Expert

Select from freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
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 tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

776 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