Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a Java function repeatedly

Tags:

java

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

like image 679
Lee Loftiss Avatar asked Jul 20 '26 11:07

Lee Loftiss


1 Answers

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.

like image 106
Adam Mihalcin Avatar answered Jul 23 '26 02:07

Adam Mihalcin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!