类java.nio.channels.ClosedByInterruptException源码实例Demo

下面列出了怎么用java.nio.channels.ClosedByInterruptException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: joyqueue   文件: StoreFileImpl.java
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;
    }
}
 
源代码2 项目: apm-agent-java   文件: SamplingProfiler.java
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();
    }
}
 
源代码3 项目: embedded-cassandra   文件: RemoteArtifact.java
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);
	}
}
 
@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;
        }
    }
}
 
源代码5 项目: netbeans   文件: Utils.java
/**
    * 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;
}
 
源代码6 项目: hadoop   文件: TestRPCWaitForProxy.java
/**
 * 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;
  }
}
 
源代码7 项目: big-c   文件: TestRPCWaitForProxy.java
/**
 * 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;
  }
}
 
源代码8 项目: appengine-gcs-client   文件: GcsServiceImpl.java
@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;
  }
}
 
源代码9 项目: x-pipe   文件: ControllableFileAbstractTest.java
@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();
}
 
源代码10 项目: jolie   文件: BTL2CapListener.java
@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();
	}
}
 
源代码11 项目: artio   文件: GatewayProcess.java
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;
}
 
源代码12 项目: SoLoader   文件: MinElf.java
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
    }
  }
}
 
源代码13 项目: appengine-gcs-client   文件: GcsServiceImpl.java
@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;
  }
}
 
源代码14 项目: ignite   文件: FileHandleManagerImpl.java
/** {@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;
}
 
源代码15 项目: ignite   文件: FilePageStore.java
/**
 * 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;
    }
}
 
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;

            }
 
源代码17 项目: hbase   文件: ExceptionUtil.java
/**
 * @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;
}
 
源代码18 项目: database   文件: Haltable.java
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;
        
    }
 
源代码19 项目: ranger   文件: RangerAdminTagRetriever.java
@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;
}
 
源代码20 项目: ranger   文件: RangerAdminUserStoreRetriever.java
@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;
}
 
源代码21 项目: appengine-gcs-client   文件: GcsServiceImpl.java
@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;
  }
}
 
源代码22 项目: agrona   文件: AgentRunnerTest.java
@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();
}
 
源代码23 项目: appengine-gcs-client   文件: GcsServiceImpl.java
@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;
  }
}
 
源代码24 项目: journalkeeper   文件: DefaultExceptionListener.java
@Override
public void onException(Throwable t) {
    try {
        throw t;
    } catch (InterruptedException | ClosedByInterruptException ignored) {
    } catch (Throwable e) {
        if (e.getCause() == null || (!(e.getCause() instanceof ClosedByInterruptException) && !(e.getCause() instanceof InterruptedException))) {
            logger.warn("{} Exception: ", name, e);
        }
    }
}
 
源代码25 项目: journalkeeper   文件: AbstractServer.java
private void flushState() {
    try {
        state.flush();
        ServerMetadata metadata = createServerMetadata();
        if (!metadata.equals(lastSavedServerMetadata)) {
            metadataPersistence.save(metadataFile(), metadata);
            lastSavedServerMetadata = metadata;
        }
    } catch (ClosedByInterruptException ignored) {
    } catch (Throwable e) {
        logger.warn("Flush exception, commitIndex: {}, lastApplied: {}, server: {}: ",
                journal.commitIndex(), state.lastApplied(), uri, e);
    }
}
 
源代码26 项目: dragonwell8_jdk   文件: LoopingTruncate.java
public static void main(String[] args) throws Throwable {
    Path path = Files.createTempFile("LoopingTruncate.tmp", null);
    try (FileChannel fc = FileChannel.open(path, CREATE, WRITE)) {
        fc.position(FATEFUL_SIZE + 1L);
        fc.write(ByteBuffer.wrap(new byte[] {0}));

        Thread th = new Thread(() -> {
            try {
                fc.truncate(FATEFUL_SIZE);
            } catch (ClosedByInterruptException ignore) {
            } catch (Exception e) {
                throw new RuntimeException(e);
            }});
        th.start();
        th.join(TIMEOUT);

        if (th.isAlive()) {
            System.err.println("=== Stack trace of the guilty thread:");
            for (StackTraceElement el : th.getStackTrace()) {
                System.err.println("\t" + el);
            }
            System.err.println("===");

            th.interrupt();
            th.join();
            throw new RuntimeException("Failed to complete on time");
        }
    } finally {
        Files.deleteIfExists(path);
    }
}
 
源代码27 项目: TencentKona-8   文件: LoopingTruncate.java
public static void main(String[] args) throws Throwable {
    Path path = Files.createTempFile("LoopingTruncate.tmp", null);
    try (FileChannel fc = FileChannel.open(path, CREATE, WRITE)) {
        fc.position(FATEFUL_SIZE + 1L);
        fc.write(ByteBuffer.wrap(new byte[] {0}));

        Thread th = new Thread(() -> {
            try {
                fc.truncate(FATEFUL_SIZE);
            } catch (ClosedByInterruptException ignore) {
            } catch (Exception e) {
                throw new RuntimeException(e);
            }});
        th.start();
        th.join(TIMEOUT);

        if (th.isAlive()) {
            System.err.println("=== Stack trace of the guilty thread:");
            for (StackTraceElement el : th.getStackTrace()) {
                System.err.println("\t" + el);
            }
            System.err.println("===");

            th.interrupt();
            th.join();
            throw new RuntimeException("Failed to complete on time");
        }
    } finally {
        Files.deleteIfExists(path);
    }
}
 
源代码28 项目: canal-1.1.3   文件: BufferedFileDataInput.java
public void seek(long seekBytes) throws FileNotFoundException, IOException, InterruptedException {
    fileInput = new FileInputStream(file);
    fileChannel = fileInput.getChannel();

    try {
        fileChannel.position(seekBytes);
    } catch (ClosedByInterruptException e) {
        throw new InterruptedException();
    }
    bufferedInput = new BufferedInputStream(fileInput, size);
    dataInput = new DataInputStream(bufferedInput);
    offset = seekBytes;
}
 
源代码29 项目: RDFS   文件: DataNode.java
/** Check if there is no space in disk 
 *  @param e that caused this checkDiskError call
 **/
protected void checkDiskError(Exception e ) throws IOException {
  if (e instanceof ClosedByInterruptException
      || e instanceof java.io.InterruptedIOException) {
    return;
  }
  LOG.warn("checkDiskError: exception: ", e);
  
  if (e.getMessage() != null &&
      e.getMessage().startsWith("No space left on device")) {
    throw new DiskOutOfSpaceException("No space left on device");
  } else {
    checkDiskError();
  }
}
 
源代码30 项目: localization_nifi   文件: SSLSocketChannel.java
private int readData(final ByteBuffer dest) throws IOException {
    final long startTime = System.currentTimeMillis();

    while (true) {
        if (interrupted) {
            throw new TransmissionDisabledException();
        }

        if (dest.remaining() == 0) {
            return 0;
        }

        final int readCount = channel.read(dest);

        if (readCount == 0) {
            if (System.currentTimeMillis() > startTime + timeoutMillis) {
                throw new SocketTimeoutException("Timed out reading from socket connected to " + hostname + ":" + port);
            }
            try {
                TimeUnit.NANOSECONDS.sleep(BUFFER_FULL_EMPTY_WAIT_NANOS);
            } catch (InterruptedException e) {
                close();
                Thread.currentThread().interrupt(); // set the interrupt status
                throw new ClosedByInterruptException();
            }

            continue;
        }

        logger.trace("{} Read {} bytes", this, readCount);
        return readCount;
    }
}
 
 类所在包
 同包方法