Properly timeout a urlconnection?

Hi,
I have been struggling to find a way to timeout a UrlConnection when it hangs on trying to connect to a site . My application has around 10 threads with each thread creating a urlconnection object and getting the inputstream. My urlconnection hangs on occasion when trying to connect to certain sites.
1. I'ved tried to create separate timer threads to launch the threads that actually make the connection. The timer threads would do a Thread.join() to the threads with the URLconnection object and do a Thread.interrupt() when it exceeds the join time limit.
This approach does not actually kill the URL connection .
And so I am left with a hanging URL connection.
2. I've also tried using Socket to connect but the timeout is only for timing out when no activity is occurring. it doesn't timeout when it hangs on trying to connect. I don't know of any way to set the timeout before the connecting action occurs.
3. I've thought about using Thread.stop() but according to the javadocs, it says this method is unsafe because it removes all the monitors.
I s there a safe way to destroy a URLconnection after a certain amount of time?
-Will

My solution was your solution 1) with the additional wrinkle that I make sure that the threads that I am going to let run away are daemon threads (xx.setDaemon(true); --> before xx.start();).
My experience is that they will eventually timeout by themselves (around 5 minutes or so; I did see a reference to 420 seconds at some point in my reading), but I am not willing to wait that long.
So I just ignore them after my Thread.join(myTimeout) period, and let the GC handle them. Seems to work ...

Similar Messages

  • Can some one give me clear answer how to set timeouts on URLConnection ?

    I am amazed why Sun did not specify a simple method like setReadTimeout
    on URLConnection or provide a way to get refernce to the underlying socket objet. By default the timeout is infinite!
    I am using JDK 1.4 and these appraoches:
    -Dsun.net.client.defaultConnectTimeout=<value in milliseconds>
    -Dsun.net.client.defaultReadTimeout=<value in milliseconds>
    also don't work.
    I do not have access to Socket object. Please help.
    I am using URLConnection in my client application on HTTPS and doing heavy load form POST processing. I tried
    Sockets as well but they don't work. URLConnection works perfectly fine except for the timeouts nightmare.

    OK this might sound crazy but you may have been onto it right from the start. I was having the exact same (frustrating) problem with the URLConnection waiting forever on a dead server and no way to terminate it. I tried something like what you said in your first post:
    System.setProperty("sun.net.client.defaultReadTimeout", "10000");
    and it worked. I played around with the number and it it was apparent to the naked eye that it was working (if you can believe that...).
    Of course, I'm using JDK 1.4.1_01 by now, so this might be different now.
    ttfn.

  • Setting Timeout  in URLConnection/HttpURLConnection

    Hi all,
    I am trying to open a connection a website using the java.net.HttpURLConnection.
    Please tell me what is the default timeout (how much time it will wait for getting reply ) and how we can change the
    default value. Please help me.
    Thanks in advance.

    This seems to be what you are looking for.
    [http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLConnection.html#setReadTimeout%28int%29|http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLConnection.html#setReadTimeout%28int%29]

  • Problem sending a httprequest to a servlet java class

    i know that entering an URL like this in the browser can call the servlet class:
    http://www.xxxxxxxx.com/RequestHandler?action=showallitems
    but.....
    what codes do i need to send a httprequest to the servlet in java coding?
    thanks again.

    You mean like a normal Java code, not HTML, Request Dispatch, or something like that?
    If so, then you will want to use a URLConnection (HttpURLConnection). First, create a java.net.URL to the location you want. Then open a connection (which returns a URLConnection - if your URL uses an http protocol it will actually use an HttpURLConnection and can be casted).
    Use the methods in java.net.HttpURLConnection to adjust the headers, and parameters, and set up the method to use. Then get the input stream to commit the request and read the response from the server.
    Make sure you read the API for URLConnection and HttpURLConnection thoroughly. There are some quirks and specific order of events that need to be followed. Also read http://www.javaworld.com/javaworld/jw-03-2001/jw-0323-traps.html for info on how to properly use a URLConnection.

  • Autoreply Timeout not working properly

    Sun Java(tm) System Messaging Server 6.1 HotFix 0.11 (built Jan 28 2005)
    libimta.so 6.1 HotFix 0.11 (built 16:16:35, Jan 28 2005)
    I saw this happen about a month ago, but wrote it off as a "weirdness", however here's the second report of it. User sets their autoreply (vacation) timeout to say 120 (5 days), however, every message sent in same day from the same sender, gets a reply. That's not how it's supposed to work. I've changed the timeout to 3 days, same thing.
    It doesn't appear to be a system wide thing (I was on vacation last week and mine was set to 3 days and there was no problem). Only certain users are affected. Where else can I investigate this problem? All info in LDIF looks correct. I've found the user.vac file for this person and it has recorded every message (even from the same sender) -so there's dups. If I look at mine from last week where it worked properly - there's only one entry per sender. Any ideas?

    Patch 116568-99 is available:Hmm, I thought that's the last patch I put on - I'm pretty sure that's what I ran....
    There are some autoreply fixes in there.
    Also, "autoreply" is different from "vacation reply".
    Autoreply will reply each time a message comes in.
    . "vacation reply" will pay attention to the timeout
    you set. Perhaps the user is simply setting the
    wrong option?So, are you saying that when someone checks the "enable automatic vacation reply" in the webclient (messenger express not UWC), that does not write the maildeliveryoption=autoreply? I thought that attribute had to be there for the vacation message to work?

  • URLConnection Timeouts

    I am using XmlRpc for my communications and sometimes, my application hangs after sending the data to the server. I am assuming the packets get lost, but even so, is there any way I can put a timeout on the URLConnection??
    I could then either re-try the request or throw an exception back to the client and let it know what is going on.
    Thanks in advance
    wwe8

    I don't have much experience with URLConnection but I'm using an HttpConnection and they're quite similar. Here's what I use to make the server hang-up without having to wait a while before time-out:
    conn.setRequestProperty("Connection", "close");
    Hope this helps!!
    Cheers,
    Omar...

  • URLConnection Timeout

              Hello All,
              I have a servlet that opens up a connection to another server using URLConnection.
              The servlet sends data and then reads the response from the connection.getOutputStream().
              The internal tests work fine. I was wondering when the servlet would time out
              on the connection if the other server takes a long time to send back a response.
              Is it associated with the keepAlive property in weblogic.properties? So far,
              in our tests, we tried blocking the response back for up to 2 minutes and the
              connection did not timeout.
              Thanks for your help.
              Sincerely,
              Richard Dedeyan
              

              The following method will complete even if nothing is sent back from the servlet to whom
              the connection is made.
              Sends a request and returns a resulting xml string
              @return the response xml as a string
              private String sendRequest( String requestURL ) // requestURL ->
              http://myhost:7001?name=Joe
              StringBuffer returnValue = new StringBuffer();
              try
              //Sending the request from Servlet_1 to Servlet_2
              // send the string to the servlet
              URL url = new URL( requestURL );
              HttpURLConnection conn = (HttpURLConnection) url.openConnection();
              log("\n--> HTTP URLConnection Request Method: " + conn.getRequestMethod());
              // get ready to read the response from the servlet.
              // this is what actually invokes the servlet!
              DataInputStream input = new DataInputStream(conn.getInputStream());
              log( "\nReading results from server:" );
              // read in each character until end-of-stream is detected
              for ( int c = input.read(); c != -1; c = input.read() )
              returnValue.append((char) c);
              log("server returned = " + returnValue.toString());
              log("\n" );
              // clean up
              input.close();
              conn.disconnect();
              catch ( Throwable e )
              log("Servlet_1::sendRequest .....");
              e.printStackTrace();
              return returnValue.toString();
              } //end sendRequest
              Richard Dedeyan wrote:
              > Hello All,
              >
              > I have a servlet that opens up a connection to another server using URLConnection.
              > The servlet sends data and then reads the response from the connection.getOutputStream().
              >
              > The internal tests work fine. I was wondering when the servlet would time out
              > on the connection if the other server takes a long time to send back a response.
              >
              > Is it associated with the keepAlive property in weblogic.properties? So far,
              > in our tests, we tried blocking the response back for up to 2 minutes and the
              > connection did not timeout.
              >
              > Thanks for your help.
              >
              > Sincerely,
              > Richard Dedeyan
              

  • Time Capsule not Broadcasting Properly/Connection Timeout

    Help!! Please!! My time capsule's wireless networking capability seems to have gone kaput. I can no longer connect any of my devices to the wireless network. The time capsule wireless network appears in the list of available networks, but none of my devices are able to connect to the network there is a connection timeout each time I attempt to connect. I've tried a hard rest and have reconfigured the time capsule from scratch. Does anyone have any idea what is going on?
    Thanks.

    If you connect your Mac to the Time Capsule using an ethernet connection, are you able to open AirPort Utility - Manual Setup?
    If yes, click the Wireless tab below the row of icons
    Change the Channel setting (it may be on Automatic now) to another setting and jot down the Channel number(s) you are using. Start at the high end of the channels. Try some different settings to see if you can find some clear airspace.
    It may be that you have a neighbor who may have installed a wireless security system and/or cameras.
    Any cordless phones there? Try turning them all off for a period as a test and then restarting your network to see if that makes any difference in your connection ability.
    Assuming that the wireless on the Time Capsule is working properly (it will likely work perfectly if you take it to the Apple store), some kind of interference is likely causing your problems.
    Some time ago, I had issues on my wireless with intermittent slowdowns and stalls. I could not figure out what the problem was until by accident, I noticed my neighbor...across the street....coming out of his house talking on his cordless phone when my wireless crashed. Nothing would work on the wireless.
    It took some coaxing, but I was able to convince him to leave his phone(s) in the house and not use them outside. No problems since.

  • Timeout problem - record is not shown properly in detail page after timeout

    Hi,
    I am using JDeveloper 10.1.3.1.0.3984
    and JHeadstart 10.1.3.1 Release 10.1.3.1.26
    I have a Master View Object where there is a field ID (for example M_VO).
    There is a page associated with M_VO (Page_M_VO.jspx)
    There is a Detail View Object (for example D_VO)
    There is a page associated with D_VO (Page_D_VO.jspx)
    There is a link from M_VO to D_VO using the field ID.
    When I open the page Page_M_VO.jspx and select an ID and go to the detail page Page_D_VO.jspx, it goes to the detail page Page_D_VO.jspx. It works fine.
    But the problem is:
    If for example I have three ID (111, 222, 333), in master page if I select 222 and go to detail page it shows the appropriate records for 222 as I selected 222 in master page. If I keep the detail page open for more than the timeout minutes specified in web.xml and then try to access the detail page again it ask for userid and password (which is fine). If I put userid and password, then it shows the detail page with the first record which is the record associated with the ID 111. But before timeout I was working with the ID 222, so it should show the record associated with ID 222 as I was working with ID 222 before timeout.
    Can anybody help me to solve this problem?
    Thanks
    Syed Jabbar
    University of Windsor
    Windsor, ON, Canada

    I would put my money on the fact that since your application is timing out, it is dropping any state that your View Objects otherwise had before the application timeout.
    So upon reauthorizing and reaccessing the application (and going directly to the detail page) the View Object is reinstantiated and only knows to go to its default data set which is 111.
    If my assumption is correct, I don't think you could really implement this without a lot of trouble.

  • Help please: URLConnection and timeout

    I want to connect to a Internet URL and retrieve the HTML code, but I have error message: "Operation timed out: connect"
    How I can resolve this?
    Thanks.
    <%
    try {
    URL theUrl = new URL("http://www.yahoo.com");
    URLConnection uc = theUrl.openConnection();
    InputStream content = uc.getInputStream();
    BufferedInputStream in = new BufferedInputStream (content);
    LineNumberReader lnr = new LineNumberReader (new InputStreamReader(in));
    String tempStr = "";
    StringBuffer str = new StringBuffer();
    while ((tempStr = lnr.readLine()) != null)
    str.append(tempStr);
    out.println(tempStr);
    in.close();
    lnr.close();
    catch(Exception e) { out.println("Error:"+e.getMessage()); }
    %>

    I was getting the same error while connecting through a proxy.
    The following lines fixed the problem:
    System.setProperty("http.proxyHost", "[your proxy's IP]");
    System.setProperty("http.proxyPort", "[your proxy's port]");
    Good Luck
    matrixPooh www.bizdisplay.com

  • URLConnection and timeout

    hi,
    i read a lot of messages on forum and i just want to know if there is a setimeout method implements in the new java jsk1.4.2 or a plugins?

    I was getting the same error while connecting through a proxy.
    The following lines fixed the problem:
    System.setProperty("http.proxyHost", "[your proxy's IP]");
    System.setProperty("http.proxyPort", "[your proxy's port]");
    Good Luck
    matrixPooh www.bizdisplay.com

  • Problem when using the Http TimeOut system parameter in JDK 1.4

    Hi,
    The JDK 1.4 URLConnection class seems to be caching the timeout values in JDK 1.4. Hence this result in a inflexibility of setting the timeout value once for the entire functioning of the JVM. The sample code is below
    public class TestUrlConnection {
         * main method
         * @param args
         public static void main(String[] args) throws Exception {
              try {
                   System.setProperty("sun.net.client.defaultReadTimeout","1000");
                   System.out.println("Testing Connection Timeout Parse I");
                   URL url =
                        new URL("http://localhost:9080/StrutsApplicationWeb/timeOutTest.do");
                   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                   System.out.println("Conn Type:" + conn.getContentType());
                   System.out.println("Conn Encoding:" + conn.getContentEncoding());
                   System.out.println("Conn Resp Code:" + conn.getResponseCode());
              } catch (SocketTimeoutException se) {
                   System.out.println("Timeout parse I");
              try {
                   System.setProperty("sun.net.client.defaultReadTimeout","25000");
                   System.out.println("Testing Connection Timeout Parse II");
                   URL url =
                        new URL("http://localhost:9080/StrutsApplicationWeb/timeOutTest.do");
                   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                   System.out.println("Conn Type:" + conn.getContentType());
                   System.out.println("Conn Encoding:" + conn.getContentEncoding());
                   System.out.println("Conn Resp Code:" + conn.getResponseCode());
              } catch (SocketTimeoutException se) {
                   System.out.println("Timeout parse II");
    The server is a URL that produces an delay of 20 secs. Hence as per above code the first parse should fail but the second one should succeed. As URLConnection is caching the timeout value, the code is not functioning properly. Do you guys think, it is ok for URLConnection to cache timeout values???

    that is odd. I thought I saw the source to
    HttpURLConnection once, and the default timeout is
    hardcoded in the code, so there was no way of setting
    the time out. maybe right, i saw that setting a system property the second time dint seem to alter the value, but made the mistake of assuming that the connection picked up the timeout value first time from the system property the first time it was defined
    >
    1.5 changes this.setConnectionTimeout(int)

  • Ageing report-ageing period doesn't appear properly

    Hi I am doing ageing report - ageing period  not coming properly- actually base date should be added with additional months(t052-zmona) depending on payment term (t052-zterm). if i give 12 months its adding as 12 days with basedate . so i need the code to convert the months into days and then add it to basedate.anybody please help me. thanks.

    Hi Daniel,
    Azure unloads your site if it is idle for the standard 20 minute timeout, which can cause slow responses for the initial site users after it is unloaded.  Enabling Always On essentially causes Azure to automatically ping your site periodically to ensure
    that it remains in a running state.  Always on is not an available option on lower end plans.  
    However in Basic or Standard mode, you can enable Always On to keep the app loaded all the time.
    It is not a known issue, I suppose in theory it could consume more CPU cycles and thus could require the deployment of more infrastructure.
    Couple of things you might want to check :
    - Increase the Instance count
    - Check the Monitor Tab in Azure Website to see how much of CPU, DataIN and Data Out time is taken for a request to the site.
    Recommend you to see this thread discussion on  Failed request tracing
    for troubleshooting on Slow requests  and a video  on  
    Troubleshooting Slow Requests with Failed Request Tracing that might help troubleshoot the slowness of website.
    Regards,
    Shirisha Paderu

  • How to make a socket connection timeout infinity in Servlet doPost method.

    I want to redirect my System.out to a file on a remote server (running Apache Web Server and Apache Tomcat). For which I have created a file upload servlet.
    The connection is established only once with the servlet and the System.out is redirected to it. Everything goes fine if i keep sending data every 10 second.
    But it is required that the data can be sent to the servlet even after 1 or 2 days. The connection should remain open. I am getting java.net.SocketTimeoutException: Read timed out Exception as the socket timeout occurs.
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.
    Following is the coding to establish a connection with the Servlet.
    URL servletURL = new URL(mURL.getProtocol(), mURL.getHost(), port, getFileUploadServletName() );
    URLConnection mCon = servletURL.openConnection();
    mCon.setDoInput(true);
    mCon.setDoOutput(true);
    mCon.setUseCaches(false);
    mCon.setRequestProperty("Content-Type", "multipart/form-data");
    In the Servlet Code I am just trying to read the input from the in that is the input stream.
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException
    BufferedInputStream in = new BufferedInputStream(req.getInputStream());
    byte [] content = new byte[1024];
    do
    read = in.read(content, 0, content.length);
    if (read > 0)
    out.write(content, 0, read);
    I have redirected the System.out to the required position.
    System.setOut(........);
    Can anyone guide me how to change the default timeout of the socket connection in my servlet class.

    I am aware of the setKeepAlive() method, but this can only used with the sockets. Here i am inside a servlet, have access to HTTPServletRequest and HTTPServletResponse and I don't know how to get access to the underlying sockets as the socket handling will be handled by the tomcat itself. If I am right there will be method in the apache tomcat 6.0.x to set this property. But till now I am not getting it.

  • Connection timeout on hotel wifi - only with MacBook8.1 (810.9)  configd plug-in:8.1 (810.9)

    I'm having a "Connection Timeout" issue while trying to connect to my hotel's WIFI.
    I bought an ex-lease refurbished white MacBook (Build 12E55 - 2.4GHz, the last 2010 model I think) a couple of weeks ago. I bought it so I could use it while on vacation in Bali, Indonesia. I've got OS X 10..8.4 installed. 
    At home in Australia, this MacBook connected to my home WIFI with absolutely no issues at all.
    Now that I'm in Bali, I'm surprised to find that every time I try to connect to the WIFI at the hotel (where I'm staying for a whole month), I get a "Connection Timeout" error. I'm surprised because my iPhone connects to the hotel WIFI with no problem at all, as does our two iPads and the Android phones that belong to other family members. It's only my MacBook that struggles, even though I get even better signal strength indicated on my MacBook compared to my other devices.
    I can connect my MacBook to my iPhone hotspot fine, though I'd prefer to use the free hotel WIFI over my very small 3G data allowance.
    So the problem isn't that my MacBook can't connect to any WIFI, because it did at home and it still can to my iPhone hotspot.
    And the problem isn't with the router, because all other devices work flawlessly.
    I've trawled many forums and articles trying to find a solution. Here's everything I've tried already, that I can remember. (Not in this order and not all at once.)
    Rebooted MacBook (duh)
    Sitting directly under the WIFI router. (It's not a signal strength issue.)
    Set up new Network > Location. Deleted Ethernet and Bluetooth PAN so it's just WIFI in the list.
    Renewed DHCP Lease countless times.
    Tried manual TCP/IP variations. It doesn't help that I'm not sure what to put in the IPv4 Address field. I do know the Subnet Mask and Router IP from looking at my iPhone network info.
    Tried using my MAC address as the DHCP Client ID. Also tried just using "1" or leaving it blank.
    I don't know what an IPv6 is either.
    Tried BootP and completely Manual setups but not really sure of the correct settings to try.
    Tried using the DNS servers that I found on my iPhone network info for the hotel WIFI. (One of them is 8.8.8.8 which I think is Google's DNS thing?)
    Tried checking Auto Proxy Discovery and Use Passive FTP Mode, since it was suggested as part of a solution in a forum thread.
    Tried changing the MTU to a couple of other settings from an article I read. I think one was around 1453 and the other was 1494 or something close to that.
    Tried resetting PRAM
    Tried resetting SMC
    Tried a variation on resetting SMC that involved pressing down the normal keys plus one extra, for 10 secs, since it worked for someone who was told to do that by an Apple Care person. (He didn't know why it worked and other forum posters thought it was supposed to have been a SMC reset.)
    Checked the Network> Wi-Fi in System Information to see if the Channel is compatible. The router uses Channel 1 and my MacBook is capable of using Channel 1.
    Checked my country profile. It's X1. I have no idea if that's good. All I know is that I'm in Indonesia not Australia and I'm having WIFI issues with this hotel network.
    Checked the PHY Mode. Supported are 802.11 a/b/g/n. The hotel router uses 802.11n.
    Made sure I was using WPA2 Personal.
    Tried deleting all WIFI-related passwords in Keychain.
    Tried deleting all Network-related preference files.
    Tried removing all LaunchDaemons and LaunchAgents.
    It's not a "lost WIFI connection when waking from sleep" issue but I tried turning off sleep anyway.
    My husband even had the nerve to unplug the hotel router (small hotel, we're the only guests at the moment) for 10 minutes hoping it will reboot. But I don't know if that's the actual modem or just a WIFI repeater thing (sorry, can't remember the right terms). It didn't work anyway.
    I've run out of options, other than just sucking it up and getting a big 3G data allowance since I'm here for a month.
    If there is anything else I can try - perhaps working out how to set up my Network manually properly, please help me out. Here is everything in System Information that might help. I'll happily provide any other info.
    Software Versions:
      CoreWLAN:

    Sorry. The topic title got mucked up when I tried to paste in my System Information. And I can't paste it in using my iPhone without it going haywire. I can provide any details you need.

Maybe you are looking for

  • Photoshop CS2 in Mac Snow Leopard: faint, pale colours when printed

    I used to use Photoshop CS on my old PPC eMac with OS 10.4.11 (Tiger), and printed succesfully on good quality glossy photo paper using an Epson Stylus Photo R340 printer. I have now upgraded to an Intel Mac mini with OS 10.8.3 (Mountain Lion). I am

  • How do I save a still that I have extracted from iMovie and save it to iPhoto?

    I'm trying to save a still that I have extracted from imovie.  So far, all I can see is that it can be saved in the imovie project.  I need to save it to iphoto.  Any help would be appreciated.  I'm running Lion and have aperture too.

  • Read a bfile and write its contents in a file stored in my hard disk

    I will try to describe my problem as clearly as I can. I have created a table that includes a LOB column "BFILE" Then I'm trying to READ the BFILE stored in our database using the DBMS_LOB package. so far so good. Now I want to write these data that

  • Hardware requirements for BOE XI 3.1

    Hello, I am looking for the hardware requirements to install BOE XI 3.1, but could not find any information in Installation guide as well as deployment guide. The information given is something like below, but if I click the link it will be redirecte

  • How to know file names & version on EBS 12.1.1

    Hi guys Please help I work with EBS 12..1.1 on HP-UX When apply patch no. 8429053 to support financial consultant ,I read the patch read me and as required I must know the file name and version as following . *3. Fixed File Names and versions* *$xla/