Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick test of google guava Settable Future
package listenablefuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.Date;
import java.util.concurrent.Executors;
public class SettableFutureTest {
private ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1,new ThreadFactoryBuilder().setDaemon(true).build()));
public static void main(String[] args) {
SettableFutureTest settableFutureTest = new SettableFutureTest();
System.out.println(Thread.currentThread().getName()+": current Date/Time : "+new Date());
ListenableFuture<Date> future = settableFutureTest.getTimeAfter5Sec();
Futures.addCallback(future, new FutureCallback<Date>() {
@Override
public void onSuccess(Date result) {
System.out.println(Thread.currentThread().getName()+": Date returned from future: "+result);
}
@Override
public void onFailure(Throwable t) {
System.out.println("ERROR : "+t.getMessage());
}
});
System.out.println(Thread.currentThread().getName()+": main thread will not block for settable to complete -> current Date/Time : "+new Date());
try {
// give a chance to executor task to complete
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private ListenableFuture<Date> getTimeAfter5Sec() {
SettableFuture<Date> dateFuture = SettableFuture.create();
executor.execute(() -> {
try {
// IO intensive work simulation
Thread.sleep(5 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Date date = new Date();
dateFuture.set(new Date(date.getTime()));
});
return dateFuture;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment