All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.koushikdutta.async.future.MultiFuture Maven / Gradle / Ivy

Go to download

Asynchronous socket, http(s) (client+server) and websocket library for android. Based on nio, not threads.

There is a newer version: 3.1.0
Show newest version
package com.koushikdutta.async.future;

import java.util.ArrayList;

/**
 * Created by koush on 2/25/14.
 */
public class MultiFuture extends SimpleFuture {
    ArrayList> callbacks;

    final FutureCallback callback = new FutureCallback() {
        @Override
        public void onCompleted(Exception e, T result) {
            ArrayList> callbacks;
            synchronized (MultiFuture.this) {
                callbacks = MultiFuture.this.callbacks;
                MultiFuture.this.callbacks = null;
            }

            if (callbacks == null)
                return;
            for (FutureCallback cb: callbacks) {
                cb.onCompleted(e, result);
            }
        }
    };

    @Override
    public MultiFuture setCallback(FutureCallback callback) {
        synchronized (this) {
            if (callbacks == null)
                callbacks = new ArrayList>();
            callbacks.add(callback);
        }
        // so, there is a race condition where this internal callback could get
        // executed twice, if two callbacks are added at the same time.
        // however, it doesn't matter, as the actual retrieval and nulling
        // of the callback list is done in another sync block.
        // one of the invocations will actually invoke all the callbacks,
        // while the other will not get a list back.

        // race:
        // 1-ADD
        // 2-ADD
        // 1-INVOKE LIST
        // 2-INVOKE NULL
        super.setCallback(this.callback);
        return this;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy