下面列出了怎么用java.nio.channels.ClosedByInterruptException的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
}
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();
}
}
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;
}
}
}
/**
* 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;
}
/**
* 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;
}
}
/**
* 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;
}
}
@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;
}
}
@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();
}
@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();
}
}
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;
}
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
}
}
}
@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;
}
}
/** {@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;
}
/**
* 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;
}
/**
* @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;
}
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;
}
@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;
}
@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;
}
@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;
}
}
@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();
}
@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;
}
}
@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);
}
}
}
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);
}
}
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);
}
}
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);
}
}
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;
}
/** 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();
}
}
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;
}
}