Skip to content

Instantly share code, notes, and snippets.

@h-hub
Created November 2, 2021 06:05
Show Gist options
  • Save h-hub/dcf0686a8fc9fed76e7307575208f583 to your computer and use it in GitHub Desktop.
Save h-hub/dcf0686a8fc9fed76e7307575208f583 to your computer and use it in GitHub Desktop.

Revisions

  1. h-hub created this gist Nov 2, 2021.
    40 changes: 40 additions & 0 deletions CallableExample.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    public class CallableExample {

    public static void main(String[] args) {

    ExecutorService executor = Executors.newFixedThreadPool(10);

    List<Future<String>> list = new ArrayList<>();

    Callable<String> callable = new HelloCallable();

    for(int i=0; i< 100; i++){
    Future<String> future = executor.submit(callable);
    list.add(future);
    }

    for(Future<String> fut : list){
    try {
    System.out.println(fut.get());
    } catch (InterruptedException | ExecutionException e) {
    System.out.println("Exception thrown: "+e.getMessage());
    }
    }

    executor.shutdown();
    }
    }

    class HelloCallable implements Callable<String> {

    @Override
    public String call() throws Exception {
    LocalDateTime now = LocalDateTime.now();
    long nanos = now.toInstant(OffsetDateTime.now().getOffset())
    .toEpochMilli();
    if(nanos % 2 == 0){
    throw new Exception("even time: "+nanos);
    }
    return LocalDateTime.now().toString();
    }
    }