Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Synchronization Issue with as*Async methods (ThreadStateException) #41

Open
joshgontijo opened this issue Oct 12, 2017 · 0 comments
Open

Comments

@joshgontijo
Copy link
Owner

From #143

Hello,
There is a synchronization issue in the method com.mashape.unirest.http.HttpClientHelper.requestAsync.
To explain the problem I will post the relevant method code here:

public static <T> Future<HttpResponse<T>> requestAsync(HttpRequest request, final Class<T> responseClass, Callback<T> callback) {
        HttpUriRequest requestObj = prepareRequest(request, true);

        CloseableHttpAsyncClient asyncHttpClient = ClientFactory.getAsyncHttpClient();

        if (!asyncHttpClient.isRunning()) { //ENTER CS
            asyncHttpClient.start();
            AsyncIdleConnectionMonitorThread asyncIdleConnectionMonitorThread = (AsyncIdleConnectionMonitorThread) Options.getOption(Option.ASYNC_MONITOR);
            asyncIdleConnectionMonitorThread.start(); // <-- this line throws ThreadStateException
        }
//... rest of the code
}

The problem is that if several threads attempt to perform requests with as*Async operations at the same time then it can happen that two threads will enter if in the line marked with ENTER_CS on the same time start the asyncHttpClient and then the asyncIdleConnectionMonitorThread. Since the asyncIdleConnectionMonitorThread's start method will be called twice - the second time will throw ThreadStateException (starting a thread that is already started).

Here is a simple program that reproduce the bug

public static void main(String[] args)  {
        int threads = 8;
        CountDownLatch letch = new CountDownLatch(1);
        for (int i = 0; i < threads; i++) {
            new Thread(() -> {
                try {
                    letch.await();
                    Unirest.get("http://www.google.com").asStringAsync().get();
                } catch (InterruptedException | ExecutionException  ex) {
                    Logger.getLogger(Bug.class.getName()).log(Level.SEVERE, null, ex);
                }

            }).start();
        }

        letch.countDown();
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant