Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save horiga/febfb8bd2ed8c4c2478b to your computer and use it in GitHub Desktop.
Save horiga/febfb8bd2ed8c4c2478b to your computer and use it in GitHub Desktop.
Google-guava library ListeningExecutorService examples
package org.horiga.study.googleguava.examples.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
public class CallableWithCallbackHandlerListenableFutureExcample {
private static Logger log = LoggerFactory
.getLogger(CallableWithCallbackHandlerListenableFutureExcample.class);
private static ListeningExecutorService es = MoreExecutors.listeningDecorator(
Executors.newCachedThreadPool(new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, "task-worker#" + RandomUtils.nextInt(100));
}}));
private static ExecutorService callbackHandlers = Executors.newCachedThreadPool(new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, "cab-handler#"
+ RandomUtils.nextInt(100));
}
});
public void test() {
log.debug(">>> test-task/start");
final CountDownLatch latch = new CountDownLatch(1);
ListenableFuture<String> future = es.submit(new Callable<String>() {
/* (non-Javadoc)
* @see java.util.concurrent.Callable#call()
*/
public String call() throws Exception {
try {
long waitMillis = Long.parseLong(RandomStringUtils.randomNumeric(5));
log.debug("process waiting.... / waitMillis={}ms", waitMillis);
if (waitMillis > 50000)
throw new IllegalStateException("system busy...");
log.debug("processing...");
Thread.sleep(waitMillis); // do anything
log.debug("process completed.");
return "callback-task finished/" + Thread.currentThread().getName();
} finally {
latch.countDown();
}
}
});
Futures.addCallback(future, new FutureCallback<String>() {
public void onSuccess(String result) {
log.info("callback process success. {}", result);
}
public void onFailure(Throwable t) {
log.warn("callback process failed.", t);
}
}, callbackHandlers);
log.debug(">>> test-task/end");
}
public static void main(String[] args) {
try {
new CallableWithCallbackHandlerListenableFutureExcample().test();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package org.horiga.study.googleguava.examples.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
public class CallableWithListenerListenableFutureExcample {
private static Logger log = LoggerFactory
.getLogger(CallableWithListenerListenableFutureExcample.class);
protected static ListeningExecutorService es = MoreExecutors.listeningDecorator(
Executors.newCachedThreadPool(new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, "task-worker#" + RandomUtils.nextInt(100));
}}));
protected static ExecutorService th_pool = Executors.newCachedThreadPool(new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, "thrd-worker#" + RandomUtils.nextInt(100));
}
});
public void test() throws Exception {
log.debug(">>> test-task/start");
final CountDownLatch latch = new CountDownLatch(1);
final ListenableFuture<String> future = es.submit(new Callable<String>() {
/* (non-Javadoc)
* @see java.util.concurrent.Callable#call()
*/
public String call() throws Exception {
try {
long waitMillis = Long.parseLong(RandomStringUtils.randomNumeric(5));
log.debug("process waiting.... / waitMillis={}ms", waitMillis);
if (waitMillis > 30000)
throw new IllegalStateException("system busy...");
log.debug("processing...");
Thread.sleep(waitMillis); // do anything
log.debug("process completed.");
return "callback-task finished/" + Thread.currentThread().getName();
} finally {
latch.countDown();
}
}
});
future.addListener(new Thread() {
public void run() {
try {
log.debug("--- start Listener: isDone={}, isCancelled={}", future.isDone(), future.isCancelled());
log.debug("Listener# future.get()={}", future.get()); // if task failed future.get returned 'java.util.concurrent.ExecutionException'
log.debug("--- end Listener");
} catch (Exception e) {
log.error("Failed", e);
}
}
}, th_pool);
log.debug(">>> test-task/end");
}
public static void main(String[] args) {
try {
new CallableWithListenerListenableFutureExcample().test();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package org.horiga.study.googleguava.examples.concurrent;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
public class MultiCallableWithCallbackHandlerListenableFutureExcample {
private static Logger log = LoggerFactory
.getLogger(MultiCallableWithCallbackHandlerListenableFutureExcample.class);
protected static ListeningExecutorService les = MoreExecutors
.listeningDecorator(Executors
.newCachedThreadPool(new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, "task-worker#"
+ RandomUtils.nextInt(100));
}
}));
protected static ExecutorService callbackHandlers = Executors
.newCachedThreadPool(new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(r, "cab-handler#"
+ RandomUtils.nextInt(100));
}
});
public void test() throws Exception {
log.debug(">>> test-task/start");
try {
final int taskCount = 5;
final CountDownLatch latch = new CountDownLatch(taskCount);
final CountDownLatch startGate = new CountDownLatch(1);
for (int i = 0; i < taskCount; i++) {
// invoked task
Futures.addCallback(les.submit(new Callable<String>() {
public String call() throws Exception {
try {
startGate.await(1000L, TimeUnit.MILLISECONDS);
long waitMillis = Long.parseLong(RandomStringUtils.randomNumeric(5));
log.debug("process waiting.... / waitMillis={}ms", waitMillis);
if (waitMillis > 50000)
throw new IllegalStateException("system busy...");
log.debug("processing...");
Thread.sleep(waitMillis); // do anything
log.debug("process completed.");
return "callback-task finished/" + Thread.currentThread().getName();
} finally {
latch.countDown();
}
}
}),
new FutureCallback<String>() {
public void onSuccess(String result) {
log.info("callback process success. Unresolved task count={}, {}", latch.getCount(), result);
if (latch.getCount() <= 0) {
log.info("#### ALL TASK FINISHED ####");
}
}
public void onFailure(Throwable t) {
log.warn("callback process failed. Unresolved task count={} : {}", latch.getCount(), t.getMessage());
if (latch.getCount() <= 0) {
log.info("#### ALL TASK FINISHED ####");
}
}
},
callbackHandlers);
}
// start all tasks
startGate.countDown();
} catch (Exception e) {
log.error("Failed", e);
}
log.debug(">>> test-task/end");
}
public static void main(String[] args) {
try {
new MultiCallableWithCallbackHandlerListenableFutureExcample()
.test();
} catch (Exception e) {
e.printStackTrace();
}
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.horiga.study</groupId>
<artifactId>guava-examples</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>guava-examples</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>15.0</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.0.11</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
</project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment