0

I have a class (lets say SocketClass) which extends AsyncTask (I am using Sockets, that's why I am using AsyncTask). I am calling that class on a different class which runs on the main thread.

SocketClass socketClass = new SocketClass(input);
socketClass.execute();
System.out.println(socketClass.getOutput());

This is my SocketClass

public class SocketClass extends AsyncTask < String, Void, Void > {
    int output;
    int input;

    public Offload(int input) {
        this.input = input;
    }

    public int getOutput() {
        return output;
    }

    public void doSomething() {
        // sockets related code
        // set value to the output variable
    }

    @Override
    protected Void doInBackground(String...voids) {
        doSomething();
        return null;
    }
}

When I run the application System.out.println(socketClass.getOutput()); will get executed before a value fetch to the output variable. Is it possible to execute System.out.println(socketClass.getOutput()); only after fetching a value to output variable in doSomething() method? There are some solutions in Stackoverflow such as Solution1 and Solution2, but I am afraid to use these because I dont know whether it will affect badly to the application since we want to hold some process which are in the main thread

VihangaAW
  • 272
  • 3
  • 13
  • 1
    Why are you spinning on an async task/thread if the main thread needs to wait for the result? That seems to defeat the purpose of having multithreading. Can you simplify your solution and remove the AsyncTask and just execute on the main thread, if you are going to wait for the result anyway? – Tore Dec 02 '20 at 05:32
  • I had to use an async task since the application doesnt allow to run sockets related code on the main thread – VihangaAW Dec 02 '20 at 05:39

1 Answers1

1

You can call AsyncTask.get() to get the result back after doInBackground completes.

new SocketClass().execute().get();

NOTE: this will cause the Main thread to hang while it waits.

Tore
  • 1,236
  • 2
  • 11
  • 21
  • Are there any other workarounds which do not affect Main thread? – VihangaAW Dec 02 '20 at 12:17
  • 1
    What else do you need to do on the main thread? It won't "affect" the main thread - the work will be done on another thread. But there is nothing to do on the main thread until that completes, at least from your description, so you must wait on the result – Tore Dec 15 '20 at 05:26