title: Running asynchronous code in java with timeout
body: <p>In a web server i wrote, each request invokes a list of actions. Some of these actions aren't as critical as others, so I would like to run them in a background thread.</p>
  
  <p>Also, since they aren't that important I don't care if one of them fails seldomly, and I don't want them to take up a thread forever, so other threads would be available to process the next batch.</p>
  
  <p>So, I would like to have a thread pool (e.g.: 10 threads) and hand out a thread to each background task like this. Limit each thread to 1 second, and if it doesn't finish by that time, just kill it, and be available for the next task to come in.</p>
  
  <p>How would I go about doing this ?</p>
  
  <p>So far, this is what I have :</p>
  
  <pre><code>public class AsyncCodeRunner {
  
      private static final ExecutorService executor = Executors.newFixedThreadPool(10);
  
      public void Run(Callable&lt;Void&gt; callableCode, int timeout) {
  
          final int threadTimeout = 10;
          Future&lt;Void&gt; callableFuture = executor.submit(callableCode);
  
          try {
              callableFuture.get(threadTimeout, TimeUnit.SECONDS);
          } catch (Exception e) {
              logger.Info("Thread was timed out", e);
          }
      }
  }
  </code></pre>
  
  <p>And I want to use this class like this :</p>
  
  <pre><code>public void processRequest(RequestObject request) {
  
      // do some important processing
  
      // throw some less important processing to background thread
      (new AsyncCodeRunner()).Run(new Callable&lt;Void&gt; () {
          @Override
          public Void call() throws Exception {
              // do something...
              return null;
          }
      }, 1); // 1 second timeout
  
      // return result (without waiting for background task)
      return;
  
  }
  </code></pre>
  
  <p>Will this work like I want it to ? Or how should I change it so it would ?<br/>
  And what happens if I call <code>Run()</code> but there are no available threads in the threadpool to hand out ?</p>