Created
November 9, 2016 13:05
-
-
Save senarukana/c2e03cbc58c6bcef97cc04b68778d326 to your computer and use it in GitHub Desktop.
cancelation in java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.indeed.taz.downloader; | |
import com.google.common.base.Function; | |
import com.google.common.base.Predicate; | |
import com.google.common.collect.FluentIterable; | |
import org.springframework.core.task.AsyncTaskExecutor; | |
import org.springframework.core.task.SimpleAsyncTaskExecutor; | |
import java.io.IOException; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.concurrent.Callable; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.Future; | |
/** | |
* @author zheli | |
*/ | |
public class InterruptedTester { | |
private static void test() { | |
final AsyncTaskExecutor pool = new SimpleAsyncTaskExecutor(); | |
final Function<Integer, Future<Boolean>> download = new Function<Integer, Future<Boolean>>() { | |
@Override | |
public Future<Boolean> apply(Integer e) { | |
return pool.submit(new Callable<Boolean>() { | |
@Override | |
public Boolean call() throws IOException { | |
try { | |
Thread.sleep(10000000); | |
} catch (InterruptedException e1) { | |
System.out.println("canceled!!"); | |
} | |
return true; | |
} | |
}); | |
} | |
}; | |
final Predicate<Future<Boolean>> unsuccessful = new Predicate<Future<Boolean>>() { | |
@Override | |
public boolean apply(final Future<Boolean> heapDumpDownload) { | |
try { | |
return heapDumpDownload.get(); | |
} catch (final InterruptedException e) { | |
heapDumpDownload.cancel(true); | |
return true; | |
} catch (ExecutionException e) { | |
return true; | |
} | |
} | |
}; | |
List<Integer> list = new ArrayList<>(); | |
list.add(1); | |
list.add(2); | |
System.out.println(FluentIterable.from(list).transform(download).filter(unsuccessful)); | |
} | |
public static void main(String[] args) throws InterruptedException { | |
final Thread t = new Thread() { | |
@Override | |
public void run() { | |
test(); | |
} | |
}; | |
t.start(); | |
Thread.sleep(100); | |
t.stop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment