0

I have been working with threads to send a GET request to a link (all good). However, I need it to run asynchronously, so I made a new thread and ran it. Problem is I need it to return the value returnVar[0] after the thread is done executing. I have tried while loops with !thread.isActive but of course, the method body needs a return statement. I have tried CountdownLatches which you are about to see, but they pause the main thread which I DON'T want. Any ideas are greatly appreciated.

Code:

    public String getUUID(String username) {
    final String[] returnVar = {"ERROR"};
    final CountDownLatch latch = new CountDownLatch(1);

    Thread thread = new Thread(() -> {

        final String[] response = {"ERROR"};
        final JSONObject[] obj = new JSONObject[1];

        response[0] = ConnectionsManager.sendGet("https://api.mojang.com/users/profiles/minecraft/" + username);

        try {
            obj[0] = (JSONObject) new JSONParser().parse(response[0]);
            returnVar[0] = (String) obj[0].get("id");
        } catch (ParseException e) {
            e.printStackTrace();
        }

        latch.countDown();
    });

    thread.start();


    try {
        latch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return returnVar[0];
}
LeSweq
  • 11
  • 1

2 Answers2

1

I think you should consider using a Callable instead of a Runnable. See this thread for explanation and examples.

Also, it's a little strange that you are using the CountDownLatch with one thread. The latch is useful to make sure multiple threads are started as uniformly as possible rather than some threads getting a 'head start' in a more traditional startup.

Community
  • 1
  • 1
Kedar Mhaswade
  • 4,535
  • 2
  • 25
  • 34
0

this is an improper use of Threads.

your code runs exactly like the below code :

public String getUUID(String username) {
    String response = ConnectionsManager.sendGet("https://api.mojang.com/users/profiles/minecraft/" + username);
    try {
        return (String) ((JSONObject) new JSONParser().parse(response)).get("id");
    } catch (ParseException e) {
        return "ERROR";
    }
}

there are several options to make async call.

one option is to use CompletableFuture :

CompletableFuture.supplyAsync(getUUID("username")).thenAccept(new Consumer<String>() {
    @Override
    public void accept(String response) {
        // response of async HTTP GET
    }
});

learn more :

Community
  • 1
  • 1
FaNaJ
  • 1,329
  • 1
  • 16
  • 39