Solved

URLConnection blocked

Posted on 2002-06-26
6
676 Views
Last Modified: 2009-12-16
I have two URLConnections opened at the same time in my java applet.  One waits up to 1 minute for a webpage to return, while the other gets a web page and returns almost instantly.  I find that after the applet has made several requests for a web page it deadlocks.  The deadlock appears to be caused by the long waiting URLConnection blocking in the getInputStream function which stops the other quick URL connections from being created.  Does anyone know how a url connection is implemented lower down.  Is a deadlock occuring? Is URLConnection sharing one socket or stream or something?

0
Comment
Question by:msbroadf
6 Comments
 
LVL 92

Expert Comment

by:objects
ID: 7112454
are the two connections made in one thread?  If so, then certainly one will block the other.
Can you post the relevant part of your code so we can see whats going on.
0
 
LVL 9

Expert Comment

by:Ovi
ID: 7112767
Put every connection in a separate thread which will not block the main thread, and synchronize them if you need to. Can you post sample code from your applet ?
0
 

Author Comment

by:msbroadf
ID: 7115192
public class Engine extends Thread
{
  private volatile boolean shutdown;
  ...
  ...

  public void run()
  {
    while (!shutdown)
    {
      String line = getTunnelLine()
      if (!shutdown) processLine(line);
    }
     
  /**
   * Opens the connection to the proxy
   */
  private URLConnection openTunnel(String file)
  {
    URLConnection result;
   
    try
    {
      URL url = new URL("http" + (applet.secure ? "s" : "") + "://" + tunnelHost + ":" + (applet.secure ? "443" : new Integer(tunnelPort).toString().trim()) + file);
      result = url.openConnection();
    }
    catch (Exception e)
    {
      System.err.println("openTunnel:" + e);
      result = null;
    }
    return result;
  }

  /**
   * Gets a line of data from the HTTP tunnel
   * This function gets the long HTML page
   * and blocks all other openTunnel request
   * from executing. It is called from the engine
   * run().
   */
  private String getTunnelLine()
  {
    String result = "";
   
    if (getLineBuffer.size() > 0)
    {
      result = (String) getLineBuffer.firstElement();
      getLineBuffer.removeElementAt(0);
    }
    else
    {      
      URLConnection conn = openTunnel("/csd/proxy.cgi?cssesstoken=" + cssesstoken + "&unum=" + uniqueNum++ + "&csconnectionstyle=sendandclose");
      if (conn != null)
      {
        conn.setAllowUserInteraction(true);
        conn.setUseCaches(false);
        conn.setDoInput(true);
        if (connectTunnel(conn))
        {
          applet.message(applet.getResourceString("r50"));
          BufferedReader br = getBufferedReader(conn);
          if (br != null)
          {
            String lines = readBufferedReader(br);
            if (lines != null)
            {
              last_io = new Date();
              result = parseLines(lines);
              if (debugIn) System.err.println("In =" + result);
            }
            else
              error = true;  
            closeBufferedReader(br);
          }
          else
            error = true;
        }
        else
          error = true;
        closeTunnel(conn);
      }
      else
        error = true;
    }
    return result;
  }


  /**
   * The tunnel outline calls the quick
   * html page.
   * Tunnel the data sent to the server
   * so it looks like an HTTP POST request.  This
   * function is called when the user clicks buttons
   * on the applet to send data back to the server
   * however. It cant get bufferedreader after a while
   * because getTunnelLine is also blocking on get
   * buffered reader
   */
  public void tunnelOutline(String data)
  {
    PrintWriter out = null;
    BufferedReader in = null;
    boolean success;

    String postData = "cssesstoken=" + cssesstoken + "&" + "cschatinput=" + encode(data) + "&" + "csconnectionstyle=sendonly\r\n";
    if (useProxy)
    {
      URLConnection conn = openTunnel("/CSJava/CSCPROXY.CGI?cssesstoken=" + cssesstoken + "&cschatinput=" + encode(data) + "&csconnectionstyle=sendonly");
      if (conn != null)
      {
        conn.setUseCaches(false);
        conn.setDoInput(true);
        if (connectTunnel(conn))
          in = getBufferedReader(conn);
        else
          error = true;
        closeTunnel(conn);
      }
      else
        error = true;
    }
    else
    {
      Socket s = getSocket(tunnelHost, tunnelPort);
      if (s != null)
      {
        out = getPrintWriter(s, true);
        in = getBufferedReader(s);
        out.print("POST /CSJava/CSCPROXY.CGI HTTP/1.1\r\n" +
                  "Host: " + tunnelHost + ":" + tunnelPort + "\r\n" +
                  "Content-type: application/x-www-form-urlencoded\r\n" +
                  "Content-length: " + postData.length() + "\r\n\r\n");
        out.print(postData);
        out.flush();
      }
    }
    if (in != null)
    {
      try
      {
        StringBuffer buf = new StringBuffer();
        int input;
        while ((input = in.read()) > -1)
          buf.append((char)input);
        if (!useProxy) out.close();
        in.close();
      }
      catch (Exception e)
      {
        error = true;
      }  
    }
    if (error && debugOut) System.err.println(data + " may not have been sent");
  }

  private BufferedReader getBufferedReader(URLConnection conn)
  {
    BufferedReader result;
   
    try
    {
      result = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    }
    catch (Exception e)
    {
      System.err.println("getBufferedReader error: " + e.getMessage());
      result = null;
    }
    return result;
  }

}
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 92

Expert Comment

by:objects
ID: 7115483
Can't see any obvious problem in your code.
Have you checked what your server is recieving and whether it is blocking?
0
 
LVL 16

Accepted Solution

by:
heyhey_ earned 100 total points
ID: 7121140
some browsers limit the numbers of simultaneous URLConnection, if I remember correctly IE allows only 4 simultaneous connections. so if there are 4 connections that for some reason stay opened, fifth one will "block forever".


install naviscope proxy from www.naviscope.com to track the connection number visually.
0
 
LVL 35

Expert Comment

by:girionis
ID: 8893401
No comment has been added lately, so it's time to clean up this TA.

I will leave a recommendation in the Cleanup topic area that this question is:

- points to heyhey_

Please leave any comments here within the
next seven days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER !

girionis
Cleanup Volunteer
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Unexpected HttpURLConnection connection behavior 2 84
advertisement module in core php 4 144
backtracking recursion  code 19 53
Java Loop 6 48
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

911 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

20 Experts available now in Live!

Get 1:1 Help Now