java.nio.channels.ClosedByInterruptException Java Examples

The following examples show how to use java.nio.channels.ClosedByInterruptException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GcsServiceImpl.java    From appengine-gcs-client with Apache License 2.0 6 votes vote down vote up
@Override
public void update(final GcsFilename source, final GcsFileOptions fileOptions)
    throws IOException {
  try {
    RetryHelper.runWithRetries(new Callable<Void>() {
      @Override
      public Void call() throws IOException {
        long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt();
        raw.copyObject(source, source, fileOptions, timeout);
        return null;
      }
    }, options.getRetryParams(), exceptionHandler);
  } catch (RetryInterruptedException ex) {
    throw new ClosedByInterruptException();
  } catch (NonRetriableException e) {
    Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
    throw e;
  }
}
 
Example #2
Source File: GcsServiceImpl.java    From appengine-gcs-client with Apache License 2.0 6 votes vote down vote up
@Override
public GcsOutputChannel createOrReplace(
    final GcsFilename filename, final GcsFileOptions fileOptions) throws IOException {
  try {
    RawGcsCreationToken token = RetryHelper.runWithRetries(new Callable<RawGcsCreationToken>() {
      @Override
      public RawGcsCreationToken call() throws IOException {
        long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt();
        return raw.beginObjectCreation(filename, fileOptions, timeout);
      }
    }, options.getRetryParams(), exceptionHandler);
    return new GcsOutputChannelImpl(
        raw, token, options.getRetryParams(), options.getDefaultWriteBufferSize(),
        options.getHttpHeaders());
  } catch (RetryInterruptedException ex) {
    throw new ClosedByInterruptException();
  } catch (NonRetriableException e) {
    Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
    throw e;
  }
}
 
Example #3
Source File: FileHandleManagerImpl.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public FileWriteHandle nextHandle(SegmentIO fileIO, RecordSerializer serializer) throws IOException {
    SegmentedRingByteBuffer rbuf;

    if (mmap) {
        MappedByteBuffer buf = fileIO.map((int)maxWalSegmentSize);

        rbuf = new SegmentedRingByteBuffer(buf, metrics);
    }
    else
        rbuf = currentHandle().buf.reset();

    try {
        return new FileWriteHandleImpl(
            cctx, fileIO, rbuf, serializer, metrics, walWriter, 0,
            mode, mmap, false, fsyncDelay, maxWalSegmentSize
        );
    }
    catch (ClosedByInterruptException e) {
        if (rbuf != null)
            rbuf.free();
    }

    return null;
}
 
Example #4
Source File: FilePageStore.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes header and writes it into the file store.
 *
 * @return Next available position in the file to store a data.
 * @throws IOException If initialization is failed.
 */
private long initFile(FileIO fileIO) throws IOException {
    try {
        ByteBuffer hdr = header(type, dbCfg.getPageSize());

        fileIO.writeFully(hdr);

        //there is 'super' page in every file
        return headerSize() + dbCfg.getPageSize();
    }
    catch (ClosedByInterruptException e) {
        // If thread was interrupted written header can be inconsistent.
        lock.writeLock().lock();

        try {
            Files.delete(pathProvider.apply());

            fileExists = false;
        }
        finally {
            lock.writeLock().unlock();
        }

        throw e;
    }
}
 
Example #5
Source File: StressTestConcurrentRestApiRequests.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private boolean isTerminationByInterrupt(final Throwable cause) {

                if (InnerCause.isInnerCause(cause, InterruptedException.class))
                    return true;
                if (InnerCause.isInnerCause(cause, CancellationException.class))
                    return true;
                if (InnerCause.isInnerCause(cause,
                        ClosedByInterruptException.class))
                    return true;
                if (InnerCause.isInnerCause(cause, BufferClosedException.class))
                    return true;
                if (InnerCause.isInnerCause(cause, QueryTimeoutException.class))
                    return true;

                return false;

            }
 
Example #6
Source File: ExceptionUtil.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * @return an InterruptedIOException if t was an interruption, null otherwise
 */
public static InterruptedIOException asInterrupt(Throwable t) {
  if (t instanceof SocketTimeoutException) {
    return null;
  }

  if (t instanceof InterruptedIOException) {
    return (InterruptedIOException) t;
  }

  if (t instanceof InterruptedException || t instanceof ClosedByInterruptException) {
    InterruptedIOException iie =
        new InterruptedIOException("Origin: " + t.getClass().getSimpleName());
    iie.initCause(t);
    return iie;
  }

  return null;
}
 
Example #7
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
    * Converts an input file stream into a char sequence.
    *
    * @throws IOException
    */
   static CharBuffer getCharSequence(final FileInputStream stream, Charset encoding) throws IOException {
       FileChannel channel = stream.getChannel();
       ByteBuffer bbuf = ByteBuffer.allocate((int) channel.size());
       try {
           channel.read(bbuf, 0);
       } catch (ClosedByInterruptException cbie) {
           return null;        //this is actually okay
       } finally {
           channel.close();
       }
       bbuf.rewind();
       CharBuffer cbuf = encoding.decode(bbuf);

       return cbuf;
}
 
Example #8
Source File: Haltable.java    From database with GNU General Public License v2.0 6 votes vote down vote up
static public boolean isTerminationByInterrupt(final Throwable cause) {
    	
        if (InnerCause.isInnerCause(cause, InterruptedException.class))
            return true;
        if (InnerCause.isInnerCause(cause, CancellationException.class))
            return true;
        if (InnerCause.isInnerCause(cause, ClosedByInterruptException.class))
            return true;
        if (InnerCause.isInnerCause(cause, BufferClosedException.class))
            return true;
        /*
         * Note: We can not treat this as normal termination or the query will
         * fail to report out the openrdf QueryInterruptedException.
         */
//        if (InnerCause.isInnerCause(cause, QueryTimeoutException.class))
//            return true;

        return false;
        
    }
 
Example #9
Source File: MinElf.java    From SoLoader with Apache License 2.0 6 votes vote down vote up
public static String[] extract_DT_NEEDED(File elfFile) throws IOException {
  int failureCount = 0;
  while (true) {
    FileInputStream is = new FileInputStream(elfFile);
    try {
      return extract_DT_NEEDED(is.getChannel());
    } catch (ClosedByInterruptException e) {
      // Make sure we don't loop infinitely
      if (++failureCount > 3) {
        throw e;
      }

      // Some other thread interrupted us. We need to clear the interrupt
      // flag (via calling Thread.interrupted()) and try again. This is
      // especially important since this is often used within the context of
      // a static initializer. A failure here will get memoized resulting in
      // all future attempts to load the same class to fail.
      Thread.interrupted();
      Log.e(TAG, "retrying extract_DT_NEEDED due to ClosedByInterruptException", e);
    } finally {
      is.close(); // Won't throw
    }
  }
}
 
Example #10
Source File: SocketChannelOutputStream.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void write(final byte[] b, final int off, final int len) throws IOException {
    final ByteBuffer buffer = ByteBuffer.wrap(b, off, len);

    final int timeoutMillis = this.timeout;
    long maxTime = System.currentTimeMillis() + timeoutMillis;
    int bytesWritten;
    while (buffer.hasRemaining()) {
        bytesWritten = channel.write(buffer);
        if (bytesWritten == 0) {
            if (System.currentTimeMillis() > maxTime) {
                throw new SocketTimeoutException("Timed out writing to socket");
            }
            try {
                TimeUnit.NANOSECONDS.sleep(CHANNEL_FULL_WAIT_NANOS);
            } catch (InterruptedException e) {
                close();
                Thread.currentThread().interrupt(); // set the interrupt status
                throw new ClosedByInterruptException(); // simulate an interrupted blocked write operation
            }
        } else {
            maxTime = System.currentTimeMillis() + timeoutMillis;
        }
    }
}
 
Example #11
Source File: RangerAdminTagRetriever.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceTags retrieveTags(long lastKnownVersion, long lastActivationTimeInMillis) throws Exception {

	ServiceTags serviceTags = null;

	if (adminClient != null) {
		try {
			serviceTags = adminClient.getServiceTagsIfUpdated(lastKnownVersion, lastActivationTimeInMillis);
		} catch (ClosedByInterruptException closedByInterruptException) {
			LOG.error("Tag-retriever thread was interrupted while blocked on I/O");
			throw new InterruptedException();
		} catch (Exception e) {
			LOG.error("Tag-retriever encounterd exception, exception=", e);
			LOG.error("Returning null service tags");
		}
	}
	return serviceTags;
}
 
Example #12
Source File: RangerAdminUserStoreRetriever.java    From ranger with Apache License 2.0 6 votes vote down vote up
@Override
public RangerUserStore retrieveUserStoreInfo(long lastKnownVersion, long lastActivationTimeInMillis) throws Exception {

    RangerUserStore rangerUserStore = null;

    if (adminClient != null) {
        try {
            rangerUserStore = adminClient.getUserStoreIfUpdated(lastKnownVersion, lastActivationTimeInMillis);
        } catch (ClosedByInterruptException closedByInterruptException) {
            LOG.error("UserStore-retriever thread was interrupted while blocked on I/O");
            throw new InterruptedException();
        } catch (Exception e) {
            LOG.error("UserStore-retriever encounterd exception, exception=", e);
            LOG.error("Returning null userstore info");
        }
    }
    return rangerUserStore;
}
 
Example #13
Source File: TestRPCWaitForProxy.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * This test sets off a blocking thread and then interrupts it, before
 * checking that the thread was interrupted
 *
 * @throws Throwable any exception other than that which was expected
 */
@Test(timeout = 10000)
public void testInterruptedWaitForProxy() throws Throwable {
  RpcThread worker = new RpcThread(100);
  worker.start();
  Thread.sleep(1000);
  assertTrue("worker hasn't started", worker.waitStarted);
  worker.interrupt();
  worker.join();
  Throwable caught = worker.getCaught();
  assertNotNull("No exception was raised", caught);
  // looking for the root cause here, which can be wrapped
  // as part of the NetUtils work. Having this test look
  // a the type of exception there would be brittle to improvements
  // in exception diagnostics.
  Throwable cause = caught.getCause();
  if (cause == null) {
    // no inner cause, use outer exception as root cause.
    cause = caught;
  }
  if (!(cause instanceof InterruptedIOException)
      && !(cause instanceof ClosedByInterruptException)) {
    throw caught;
  }
}
 
Example #14
Source File: BTL2CapListener.java    From jolie with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void run() {
	try {
		L2CAPConnection clientConnection;
		CommChannel channel;
		while( (clientConnection = connectionNotifier.acceptAndOpen()) != null ) {
			channel = new BTL2CapCommChannel(
				clientConnection,
				inputPort().location(),
				createProtocol() );
			channel.setParentInputPort( inputPort() );
			interpreter().commCore().scheduleReceive( channel, inputPort() );
			channel = null; // Dispose for garbage collection
		}
	} catch( ClosedByInterruptException ce ) {
		try {
			connectionNotifier.close();
		} catch( IOException ioe ) {
			ioe.printStackTrace();
		}
	} catch( IOException e ) {
		e.printStackTrace();
	}
}
 
Example #15
Source File: TestRPCWaitForProxy.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * This test sets off a blocking thread and then interrupts it, before
 * checking that the thread was interrupted
 *
 * @throws Throwable any exception other than that which was expected
 */
@Test(timeout = 10000)
public void testInterruptedWaitForProxy() throws Throwable {
  RpcThread worker = new RpcThread(100);
  worker.start();
  Thread.sleep(1000);
  assertTrue("worker hasn't started", worker.waitStarted);
  worker.interrupt();
  worker.join();
  Throwable caught = worker.getCaught();
  assertNotNull("No exception was raised", caught);
  // looking for the root cause here, which can be wrapped
  // as part of the NetUtils work. Having this test look
  // a the type of exception there would be brittle to improvements
  // in exception diagnostics.
  Throwable cause = caught.getCause();
  if (cause == null) {
    // no inner cause, use outer exception as root cause.
    cause = caught;
  }
  if (!(cause instanceof InterruptedIOException)
      && !(cause instanceof ClosedByInterruptException)) {
    throw caught;
  }
}
 
Example #16
Source File: GcsServiceImpl.java    From appengine-gcs-client with Apache License 2.0 6 votes vote down vote up
@Override
public void copy(final GcsFilename source, final GcsFilename dest)
    throws IOException {
  try {
    RetryHelper.runWithRetries(new Callable<Void>() {
      @Override
      public Void call() throws IOException {
        long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt();
        raw.copyObject(source, dest, null, timeout);
        return null;
      }
    }, options.getRetryParams(), exceptionHandler);
  } catch (RetryInterruptedException ex) {
    throw new ClosedByInterruptException();
  } catch (NonRetriableException e) {
    Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
    throw e;
  }
}
 
Example #17
Source File: AgentRunnerTest.java    From agrona with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotReportRethrownClosedByInterruptException() throws Exception
{
    when(mockAgent.doWork()).thenAnswer(
        (inv) ->
        {
            try
            {
                throw new ClosedByInterruptException();
            }
            catch (final ClosedByInterruptException ex)
            {
                LangUtil.rethrowUnchecked(ex);
            }

            return null;
        });

    assertExceptionNotReported();
}
 
Example #18
Source File: ControllableFileAbstractTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
@Test
public void testInterupt() throws IOException {

    Thread.currentThread().interrupt();

    RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");

    try {
        randomAccessFile.getChannel().size();
        Assert.fail();
    } catch (ClosedByInterruptException e) {
        //expected
    }

    file.length();

    //clear interrupt
    Thread.interrupted();
}
 
Example #19
Source File: GcsServiceImpl.java    From appengine-gcs-client with Apache License 2.0 6 votes vote down vote up
@Override
public boolean delete(final GcsFilename filename) throws IOException {
  try {
    return RetryHelper.runWithRetries(new Callable<Boolean>() {
      @Override
      public Boolean call() throws IOException {
        long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt();
        return raw.deleteObject(filename, timeout);
      }
    }, options.getRetryParams(), exceptionHandler);
  } catch (RetryInterruptedException ex) {
    throw new ClosedByInterruptException();
  } catch (NonRetriableException e) {
    Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
    throw e;
  }
}
 
Example #20
Source File: StoreFileImpl.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
private void loadRoUnsafe() throws IOException {
    if (null != pageBuffer) throw new IOException("Buffer already loaded!");
    bufferPool.allocateMMap(this);
    try {
        MappedByteBuffer loadBuffer;
        try (RandomAccessFile raf = new RandomAccessFile(file, "r");
             FileChannel fileChannel = raf.getChannel()) {
            loadBuffer =
                    fileChannel.map(FileChannel.MapMode.READ_ONLY, headerSize, file.length() - headerSize);
        }
        if( loadOnRead ) {
            loadBuffer.load();
        }
        pageBuffer = loadBuffer;
        bufferType = MAPPED_BUFFER;
        pageBuffer.clear();
        forced.set(true);
    } catch (ClosedByInterruptException cie) {
        throw cie;
    } catch (Throwable t) {
        logger.warn("Exception: ", t);
        bufferPool.releaseMMap(this);
        pageBuffer = null;
        throw t;
    }
}
 
Example #21
Source File: SamplingProfiler.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
private void profile(TimeDuration sampleRate, TimeDuration profilingDuration) throws Exception {
    AsyncProfiler asyncProfiler = AsyncProfiler.getInstance();
    try {
        String startCommand = "start,jfr,event=wall,cstack=n,interval=" + sampleRate.getMillis() + "ms,filter,file=" + jfrFile + ",safemode=" + config.getAsyncProfilerSafeMode();
        String startMessage = asyncProfiler.execute(startCommand);
        logger.debug(startMessage);
        if (!profiledThreads.isEmpty()) {
            restoreFilterState(asyncProfiler);
        }
        profilingSessions++;

        consumeActivationEventsFromRingBufferAndWriteToFile(profilingDuration);

        String stopMessage = asyncProfiler.execute("stop");
        logger.debug(stopMessage);

        processTraces();
    } catch (InterruptedException | ClosedByInterruptException e) {
        try {
            asyncProfiler.stop();
        } catch (IllegalStateException ignore) {
        }
        Thread.currentThread().interrupt();
    }
}
 
Example #22
Source File: RemoteArtifact.java    From embedded-cassandra with Apache License 2.0 6 votes vote down vote up
Resource download(URL url, ProgressListener progressListener) throws IOException {
	URLConnection connection = connect(url);
	try (InputStream is = connection.getInputStream()) {
		long totalSize = connection.getContentLengthLong();
		Path tempFile = createTempFile(url);
		progressListener.start();
		try (OutputStream os = Files.newOutputStream(tempFile)) {
			byte[] buffer = new byte[8192];
			long readBytes = 0;
			int read;
			while ((read = is.read(buffer)) != -1) {
				os.write(buffer, 0, read);
				readBytes += read;
				if (totalSize > 0 && readBytes > 0) {
					progressListener.update(readBytes, totalSize);
				}
			}
		}
		if (Thread.interrupted()) {
			throw new ClosedByInterruptException();
		}
		progressListener.finish();
		return new FileSystemResource(tempFile);
	}
}
 
Example #23
Source File: GatewayProcess.java    From artio with Apache License 2.0 6 votes vote down vote up
protected Aeron.Context configureAeronContext(final CommonConfiguration configuration)
{
    final Aeron.Context ctx = configuration.aeronContext();
    ctx.errorHandler(
        (throwable) ->
        {
            if (shouldRethrowExceptionInErrorHandler())
            {
                LangUtil.rethrowUnchecked(throwable);
            }

            if (!(throwable instanceof ClosedByInterruptException))
            {
                errorHandler.onError(throwable);
            }
        });

    return ctx;
}
 
Example #24
Source File: ConsoleService.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void run() {
	try(
		FileInputStream fis = new FileInputStream( FileDescriptor.in );
		BufferedReader stdin = new BufferedReader(
			new InputStreamReader(
				Channels.newInputStream(
					fis.getChannel() ) ) ) ) {
		String line;
		while( keepRun ) {
			line = stdin.readLine();

			if( sessionListeners ) {

				for( String s : sessionTokens.keySet() ) {
					Value v = Value.create();
					v.getFirstChild( "token" ).setValue( s );
					v.setValue( line );
					sendMessage( CommMessage.createRequest( "in", "/", v ) );
				}
			} else {
				sendMessage( CommMessage.createRequest( "in", "/", Value.create( line ) ) );
			}
		}
	} catch( ClosedByInterruptException ce ) {
	} catch( IOException e ) {
		interpreter().logWarning( e );
	}
}
 
Example #25
Source File: FileSegmentPool.java    From indexr with Apache License 2.0 5 votes vote down vote up
public void refreshLocalities() {
    try {
        // HashMap taks muti-thread risk here. Change to ConcurrentHashMap if it happens.
        Map<String, List<String>> newHostMap = new HashMap<>(segmentFdMap.size());

        RemoteIterator<LocatedFileStatus> files = fileSystem.listFiles(segmentRootPath, true);
        while (files.hasNext()) {
            LocatedFileStatus fileStatus = files.next();
            if (fileStatus.getLen() == 0) {
                continue;
            }
            String name = getSegmentName(fileStatus);
            if (name == null) {
                continue;
            }
            BlockLocation[] locations = fileStatus.getBlockLocations();
            if (locations.length != 1) {
                logger.error("A segment should only consisted by one block, now {}. Ignored: {}", locations.length, name);
                continue;
            }
            List<String> hosts = Arrays.asList(locations[0].getHosts());
            newHostMap.put(name, hosts);
        }

        hostMap = newHostMap;
    } catch (IOException e) {
        if (e instanceof ClosedByInterruptException) {
            logger.warn("Refresh [{}] segment locality failed by ClosedByInterruptException.", tableName);
            // Normally close interrupt.
            return;
        }
        String msg = e.getMessage();
        if (msg != null && Strings.equals(msg.trim(), "Filesystem closed")) {
            logger.warn("Refresh [{}] segment locality failed by Filesystem closed.", tableName);
            // Normally close interrupt.
            return;
        }
        logger.warn("Refresh [{}] segment locality failed.", tableName, e);
    }
}
 
Example #26
Source File: GcsOutputChannelImpl.java    From appengine-gcs-client with Apache License 2.0 5 votes vote down vote up
@Override
public void close() throws IOException {
  synchronized (lock) {
    if (!isOpen()) {
      return;
    }
    waitForOutstandingRequest();
    buf.flip();
    try {
      RetryHelper.runWithRetries(new Callable<Void>() {
        @Override
        public Void call() throws IOException {
          raw.finishObjectCreation(
              token, buf.slice(), retryParams.getRequestTimeoutMillisForCurrentAttempt());
          return null;
        }
      }, retryParams, GcsServiceImpl.exceptionHandler);
    } catch (RetryInterruptedException ex) {
      throw new ClosedByInterruptException();
    } catch (NonRetriableException e) {
      Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
      throw e;
    }
    token = null;
    buf = null;
  }
}
 
Example #27
Source File: GemFireMemcachedServer.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void startMemcachedServer() throws IOException, InterruptedException {
  ServerSocketChannel channel = ServerSocketChannel.open();
  final ServerSocket serverSocket = channel.socket();
  serverSocket.bind(new InetSocketAddress(SocketCreator.getLocalHost(), serverPort));
  final CountDownLatch latch = new CountDownLatch(1);
  acceptor = new Thread(new Runnable() {
    public void run() {
      for (;;) {
        Socket s = null;
        try {
          latch.countDown();
          s = serverSocket.accept();
          handleNewClient(s);
        } catch (ClosedByInterruptException e) {
          try {
            serverSocket.close();
          } catch (IOException e1) {
            e1.printStackTrace();
          }
          break;
        } catch (IOException e) {
          e.printStackTrace();
          break;
        }
      }
    }
  }, "AcceptorThread");
  acceptor.setDaemon(true);
  acceptor.start();
  latch.await();
  logger.config("GemFireMemcachedServer server started on host:"+SocketCreator.getLocalHost()+" port: "+this.serverPort);
}
 
Example #28
Source File: InterruptedStreamTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void testInterruptReadableChannel(final ReadableByteChannel channel) throws Exception {
    Thread thread = interruptMeLater();
    try {
        channel.read(ByteBuffer.allocate(BUFFER_SIZE));
        fail();
    } catch (ClosedByInterruptException expected) {
    } finally {
        confirmInterrupted(thread);
    }
}
 
Example #29
Source File: AgentRunnerTest.java    From agrona with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotReportClosedByInterruptException() throws Exception
{
    when(mockAgent.doWork()).thenThrow(new ClosedByInterruptException());

    assertExceptionNotReported();
}
 
Example #30
Source File: GcsServiceImpl.java    From appengine-gcs-client with Apache License 2.0 5 votes vote down vote up
@Override
public void createOrReplace(final GcsFilename filename, final GcsFileOptions fileOptions,
    final ByteBuffer src) throws IOException {
  if (src.remaining() > raw.getMaxWriteSizeByte()) {
    @SuppressWarnings("resource")
    GcsOutputChannel channel = createOrReplace(filename, fileOptions);
    channel.write(src);
    channel.close();
    return;
  }

  try {
    RetryHelper.runWithRetries(new Callable<Void>() {
        @Override
        public Void call() throws IOException {
          long timeout = options.getRetryParams().getRequestTimeoutMillisForCurrentAttempt();
          raw.putObject(filename, fileOptions, src, timeout);
          return null;
        }
      }, options.getRetryParams(), exceptionHandler);
  } catch (RetryInterruptedException ex) {
    throw new ClosedByInterruptException();
  } catch (NonRetriableException e) {
    Throwables.propagateIfInstanceOf(e.getCause(), IOException.class);
    throw e;
  }
}