3

I'm not a CS guru nor a Java expert, so please forgive me if the answer to the following question is obvious:

I've built a class that handles sending a query to an HTTP server, getting the response and returning that response to the caller.

My question is this; If I call that function once, and the response is taking a long time, and during the delay, I call it again, will the delayed first call interfere with the execution of the second call?

By popular demand...here is some source code:

package com.cambrothers.wms.module;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

public class ServerComm {
public HashMap<String, String> sendData(String endpoint, String requestParameters){
    HashMap<String, String> response_data = new HashMap<String, String>();

    System.out.println("GetRequest");
    if (endpoint.startsWith("http://"))
    {
        // Send a GET request to the servlet
        try
        {

            // Send data
            String urlStr = endpoint;
            if (requestParameters != null && requestParameters.length () > 0)
            {
                urlStr += "?" + requestParameters;
            }
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection ();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null)
            {
                sb.append(line);
            }
            rd.close();
            String result = sb.toString();
            String[] values = result.split("&");
            String[] kp = null;
            for(int i =0; i < values.length ; i++){
                kp = values[i].split("=");
                response_data.put(kp[0], kp[1]);
            }

        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    return response_data;
}
}

take care

Vinesh
  • 933
  • 2
  • 7
  • 22
Lee Loftiss
  • 3,035
  • 7
  • 45
  • 73

3 Answers3

2

The level of complexity you're describing is more than the typical beginner-to-medium level programmer takes on outside of a university course, which is good. But let's look at what your question implies.

You say that "I call that function once, and the response is taking a long time." So I think it's safe to assume that you're using a synchronous request function that doesn't return until the response comes back from the server.

Then you say that "during the delay, I call it again." That means that you're using threading, a concept that I describe in high-level detail in this SO answer. If you're unfamiliar, stop right now, read up on threads and really understand them before trying to write the code that your question describes. Familiar? Keep reading.

Now to your actual question.

will the delayed first call interfere with the execution of the second call?

No, there will be no interference from the kernel and JVM's point of view, because separate threads execute separately. However, from a practical standpoint, whether or not there will be interference depends completely on your code. Thread safety is a large topic that is too big to explain in a single StackOverflow answer, but it is the key here. I can give some pointers, though. Remember that these pointers refer to the function doing the HTTP fetching.

  1. If your HTTP fetching function is reentrant, it is automatically threadsafe. To be reentrant, the function must not reference any static or global data that might be mutated, and must not call any non-reentrant code. It's quite possible that your function doesn't reference static data, but the HTTP library you're using isn't reentrant, so your HTTP fetching function isn't reentrant either.

  2. If your HTTP fetching function and/or its caller uses proper locking (getting locking right is usually a really hard problem, and college courses might spend two weeks' worth of lectures on locking, avoiding deadlock, etc.), the overall process is threadsafe. I know that "proper locking" is defined as "locking that makes the process threadsafe," so this isn't terribly helpful, but a more useful rule is to lock around any critical section. If two threads might access (and one or both might mutate) a shared resource, then you need to lock around access to that shared resource. Note that you don't only need to lock around write access to the resource, but around read access as well.

  3. If you use more exotic constructs like lock-free data structures, and you show correctness, then your program is correct. These are even harder to get right, though.

Note that if all your program data and resources are immutable, all functions are reentrant by default, meaning that your program is automatically threadsafe. In practice a program where all data and resources are completely immutable leaves a little to be desired, but if you constrain the mutability to a small region of the program and prove thread-safety of that region, your entire program is still threadsafe.

Community
  • 1
  • 1
Adam Mihalcin
  • 14,242
  • 4
  • 36
  • 52
  • Thanks for your detailed answer. I know about threads from my .NET development. In that case, I would have just created a new thread and sent the function on its merry way. I'm thinking that maybe I will just create a new class instance each time I need to call the server since it won't be done very often. I think someone before you basically gave the same answer, so, in fairness, I should accept their answer...but I will definitely upvote your great response. – Lee Loftiss May 30 '12 at 04:10
  • @LeeLoftiss I see. Then, the short answer that's useful to you is "threads in Java are like threads in any other programming language, and behave the same way. In today's operating systems, the building blocks for the thread abstraction are built in to the kernel anyway, so threading in Java, .NET, and native C/C++ will look similar." – Adam Mihalcin May 30 '12 at 04:30
0

Yes and No. But i see that this is tagged Java, assume that you are calling a HTTP Servlet?

The application server would spawn / get a pooled thread to service each individual call / request.

The rest of your user specific implementation (e.g. modifying / accessing static objects) will determine whether your new calls are affecting your previous calls.

Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215
0
will the delayed first call interfere with the execution of the second call?

This is entirely dependent on the implementation of both your function and the server code (the HTTP server). It is impossible to answer this question without more information.

csauve
  • 5,904
  • 9
  • 40
  • 50