Search code examples
javajava-threads

Network Thread to communicate with UI Thread


I've created a class for multi threading in a Java application.

import java.util.concurrent.Executor; import java.util.concurrent.Executors;

public class AppThreads {

private static final Object LOCK = new Object();
private static AppThreads sInstance;
private final Executor diskThread;
private final Executor uiThread;
private final Executor networkThread;

private AppExecutors(Executor diskThread, Executor networkThread, Executor uiThread) {
    this.diskThread = diskThread;
    this.networkThread = networkThread;
    this.uiThread = uiThread;
}

public static AppExecutors getInstance() {
    if (sInstance == null) {
        synchronized (LOCK) {
            sInstance = new AppExecutors(Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(4),
                    new MainThreadExecutor());
        }
    }
    return sInstance;
}

public Executor diskThread() {
    return diskThread;
}

public Executor networkThread() {
    return networkThread;
}

private static class MainThreadExecutor implements Executor {
    @Override
    public void execute(Runnable command) {
        command.run();
    }
}

}

I am initiating a different thread as

public void getUsers(AppThreads executors) {
executors.networkThread().execute(() -> {
    //Some DB operations
    //getting server response code  
HttpURLConnection con = (HttpURLConnection) url.openConnection();
...
...
..
int response=con.getResponseCode();
    }
}

How uiThread will know the value of int response which is being executed in networkThread?


Solution

  • One simple solution: create some kind of callback, for example:

    public interface Callback
    {
        void done(int response);
    }
    

    Pass the callback to your getUsers method. When you get your response code, you are able to call callback.done(response).

    An alternative would be to create some kind of event / listener as @Jure mentionend.