IsolatedOutputStream.java

  1. /*
  2.  * Copyright (C) 2016, Google Inc. and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */

  10. package org.eclipse.jgit.util.io;

  11. import java.io.IOException;
  12. import java.io.InterruptedIOException;
  13. import java.io.OutputStream;
  14. import java.util.concurrent.ArrayBlockingQueue;
  15. import java.util.concurrent.Callable;
  16. import java.util.concurrent.ExecutionException;
  17. import java.util.concurrent.ExecutorService;
  18. import java.util.concurrent.Future;
  19. import java.util.concurrent.RejectedExecutionException;
  20. import java.util.concurrent.ThreadFactory;
  21. import java.util.concurrent.ThreadPoolExecutor;
  22. import java.util.concurrent.TimeUnit;
  23. import java.util.concurrent.TimeoutException;
  24. import java.util.concurrent.atomic.AtomicInteger;

  25. import org.eclipse.jgit.internal.JGitText;

  26. /**
  27.  * OutputStream isolated from interrupts.
  28.  * <p>
  29.  * Wraps an OutputStream to prevent interrupts during writes from being made
  30.  * visible to that stream instance. This works around buggy or difficult
  31.  * OutputStream implementations like JSch that cannot gracefully handle an
  32.  * interrupt during write.
  33.  * <p>
  34.  * Every write (or flush) requires a context switch to another thread. Callers
  35.  * should wrap this stream with {@code BufferedOutputStream} using a suitable
  36.  * buffer size to amortize the cost of context switches.
  37.  *
  38.  * @since 4.6
  39.  */
  40. public class IsolatedOutputStream extends OutputStream {
  41.     private final OutputStream dst;
  42.     private final ExecutorService copier;
  43.     private Future<Void> pending;

  44.     /**
  45.      * Wraps an OutputStream.
  46.      *
  47.      * @param out
  48.      *            stream to send all writes to.
  49.      */
  50.     public IsolatedOutputStream(OutputStream out) {
  51.         dst = out;
  52.         copier = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS,
  53.                 new ArrayBlockingQueue<>(1), new NamedThreadFactory());
  54.     }

  55.     /** {@inheritDoc} */
  56.     @Override
  57.     public void write(int ch) throws IOException {
  58.         write(new byte[] { (byte) ch }, 0, 1);
  59.     }

  60.     /** {@inheritDoc} */
  61.     @Override
  62.     public void write(byte[] buf, int pos, int cnt)
  63.             throws IOException {
  64.         checkClosed();
  65.         execute(() -> {
  66.             dst.write(buf, pos, cnt);
  67.             return null;
  68.         });
  69.     }

  70.     /** {@inheritDoc} */
  71.     @Override
  72.     public void flush() throws IOException {
  73.         checkClosed();
  74.         execute(() -> {
  75.             dst.flush();
  76.             return null;
  77.         });
  78.     }

  79.     /** {@inheritDoc} */
  80.     @Override
  81.     public void close() throws IOException {
  82.         if (!copier.isShutdown()) {
  83.             try {
  84.                 if (pending == null || tryCleanClose()) {
  85.                     cleanClose();
  86.                 } else {
  87.                     dirtyClose();
  88.                 }
  89.             } finally {
  90.                 copier.shutdown();
  91.             }
  92.         }
  93.     }

  94.     private boolean tryCleanClose() {
  95.         /*
  96.          * If the caller stopped waiting for a prior write or flush, they could
  97.          * be trying to close a stream that is still in-use. Check if the prior
  98.          * operation ended in a predictable way.
  99.          */
  100.         try {
  101.             pending.get(0, TimeUnit.MILLISECONDS);
  102.             pending = null;
  103.             return true;
  104.         } catch (TimeoutException | InterruptedException e) {
  105.             return false;
  106.         } catch (ExecutionException e) {
  107.             pending = null;
  108.             return true;
  109.         }
  110.     }

  111.     private void cleanClose() throws IOException {
  112.         execute(() -> {
  113.             dst.close();
  114.             return null;
  115.         });
  116.     }

  117.     private void dirtyClose() throws IOException {
  118.         /*
  119.          * Interrupt any still pending write or flush operation. This may cause
  120.          * massive failures inside of the stream, but its going to be closed as
  121.          * the next step.
  122.          */
  123.         pending.cancel(true);

  124.         Future<Void> close;
  125.         try {
  126.             close = copier.submit(() -> {
  127.                 dst.close();
  128.                 return null;
  129.             });
  130.         } catch (RejectedExecutionException e) {
  131.             throw new IOException(e);
  132.         }
  133.         try {
  134.             close.get(200, TimeUnit.MILLISECONDS);
  135.         } catch (InterruptedException | TimeoutException e) {
  136.             close.cancel(true);
  137.             throw new IOException(e);
  138.         } catch (ExecutionException e) {
  139.             throw new IOException(e.getCause());
  140.         }
  141.     }

  142.     private void checkClosed() throws IOException {
  143.         if (copier.isShutdown()) {
  144.             throw new IOException(JGitText.get().closed);
  145.         }
  146.     }

  147.     private void execute(Callable<Void> task) throws IOException {
  148.         if (pending != null) {
  149.             // Check (and rethrow) any prior failed operation.
  150.             checkedGet(pending);
  151.         }
  152.         try {
  153.             pending = copier.submit(task);
  154.         } catch (RejectedExecutionException e) {
  155.             throw new IOException(e);
  156.         }
  157.         checkedGet(pending);
  158.         pending = null;
  159.     }

  160.     private static void checkedGet(Future<Void> future) throws IOException {
  161.         try {
  162.             future.get();
  163.         } catch (InterruptedException e) {
  164.             throw interrupted(e);
  165.         } catch (ExecutionException e) {
  166.             throw new IOException(e.getCause());
  167.         }
  168.     }

  169.     private static InterruptedIOException interrupted(InterruptedException c) {
  170.         InterruptedIOException e = new InterruptedIOException();
  171.         e.initCause(c);
  172.         return e;
  173.     }

  174.     private static class NamedThreadFactory implements ThreadFactory {
  175.         private static final AtomicInteger cnt = new AtomicInteger();

  176.         @Override
  177.         public Thread newThread(Runnable r) {
  178.             int n = cnt.incrementAndGet();
  179.             String name = IsolatedOutputStream.class.getSimpleName() + '-' + n;
  180.             return new Thread(r, name);
  181.         }
  182.     }
  183. }