List of usage examples for java.lang InterruptedException InterruptedException
public InterruptedException()
InterruptedException
with no detail message. From source file:com.yahoo.ads.pb.kafka.KafkaSimpleConsumer.java
private PartitionMetadata findLeader() throws InterruptedException { List<String> topics = new ArrayList<String>(); topics.add(topic);//from w ww .j a va 2s. c om for (KafkaBroker broker : replicaBrokers) { SimpleConsumer consumer = null; try { logger.debug("findLeader, try broker {}:{}", broker.host, broker.port); consumer = new SimpleConsumer(broker.host, broker.port, conf.getInt("Pistachio.Kafka.soTimeout"), conf.getInt("Pistachio.Kafka.bufferSize"), clientId + "leaderLookup"); TopicMetadataResponse resp = consumer.send(new TopicMetadataRequest(topics)); // just one topic inside the topics List<TopicMetadata> metaData = resp.topicsMetadata(); for (TopicMetadata item : metaData) { for (PartitionMetadata part : item.partitionsMetadata()) { if (part.partitionId() == partitionId) { replicaBrokers.clear(); for (Broker replica : part.replicas()) { replicaBrokers.add(new KafkaBroker(replica.host(), replica.port())); } return part; } } } } catch (Exception e) { // e could be an instance of ClosedByInterruptException as SimpleConsumer.send uses nio if (Thread.interrupted()) { logger.info("catch exception of {} with interrupted in find leader for {} - {}", e.getClass().getName(), topic, partitionId); throw new InterruptedException(); } logger.warn("error communicating with Broker {} to find leader for {} - {}", broker, topic, partitionId, e); } finally { if (consumer != null) { try { consumer.close(); } catch (Exception e) { } } } } return null; }
From source file:org.rhq.modules.plugins.wildfly10.BaseServerComponent.java
protected boolean waitUntilDown() throws InterruptedException { boolean notAnswering = false; while (!notAnswering) { Operation op = new ReadAttribute(new Address(), "release-version"); try {//from w w w.jav a 2 s . c o m Result res = getASConnection().execute(op); if (!res.isSuccess()) { // If op succeeds, server is not down notAnswering = true; } } catch (Exception e) { notAnswering = true; } if (!notAnswering) { if (context.getComponentInvocationContext().isInterrupted()) { // Operation canceled or timed out throw new InterruptedException(); } Thread.sleep(SECONDS.toMillis(1)); } } // BZ 893802: wait until server (the process) is really down HostConfiguration hostConfig = getHostConfig(); // commandLine instance is not important for determining whether the HostPort is local or not AS7CommandLine commandLine = new AS7CommandLine( new String[] { "java", "foo.Main", "org.jboss.as.host-controller" }); HostPort hostPort = hostConfig.getDomainControllerHostPort(commandLine); if (hostPort.isLocal) { // lets be paranoid here for (ProcessInfo processInfo = context.getNativeProcess();; processInfo = context.getNativeProcess()) { if (processInfo == null) { // Process not found, so it died, that's fine break; } if (!processInfo.priorSnaphot().isRunning()) { // Process info says process is no longer running, that's fine break; } if (context.getComponentInvocationContext().isInterrupted()) { // Operation canceled or timed out throw new InterruptedException(); } // Process is still running, wait a second and check again Thread.sleep(SECONDS.toMillis(1)); } } return true; }
From source file:eu.stratosphere.nephele.execution.RuntimeEnvironment.java
/** * Blocks until all input channels are closed. * * @throws IOException thrown if an error occurred while closing the input channels * @throws InterruptedException thrown if the thread waiting for the channels to be closed is interrupted *//*from w ww . j a v a 2 s . co m*/ private void waitForInputChannelsToBeClosed() throws IOException, InterruptedException { // Wait for disconnection of all output gates while (true) { // Make sure, we leave this method with an InterruptedException when the task has been canceled if (this.executionObserver.isCanceled()) { throw new InterruptedException(); } boolean allClosed = true; for (int i = 0; i < getNumberOfInputGates(); i++) { final InputGate<? extends IOReadableWritable> eig = this.inputGates.get(i); if (!eig.isClosed()) { allClosed = false; } } if (allClosed) { break; } else { Thread.sleep(SLEEPINTERVAL); } } }
From source file:org.apache.flink.runtime.execution.RuntimeEnvironment.java
/** * Blocks until all input channels are closed. * * @throws IOException thrown if an error occurred while closing the input channels * @throws InterruptedException thrown if the thread waiting for the channels to be closed is interrupted *///from ww w.j ava 2 s.c om private void waitForInputChannelsToBeClosed() throws IOException, InterruptedException { // Wait for disconnection of all output gates while (!canceled) { // Make sure, we leave this method with an InterruptedException when the task has been canceled if (this.executionObserver.isCanceled()) { throw new InterruptedException(); } boolean allClosed = true; for (int i = 0; i < getNumberOfInputGates(); i++) { final InputGate<? extends IOReadableWritable> eig = this.inputGates.get(i); if (!eig.isClosed()) { allClosed = false; } } if (allClosed) { break; } else { Thread.sleep(SLEEPINTERVAL); } } }
From source file:org.apache.tinkerpop.gremlin.server.op.AbstractEvalOpProcessor.java
/** * Called by {@link #evalOpInternal} when iterating a result set. Implementers should respect the * {@link Settings#serializedResponseTimeout} configuration and break the serialization process if * it begins to take too long to do so, throwing a {@link java.util.concurrent.TimeoutException} in such * cases.//from ww w . ja v a 2 s . c o m * * @param context The Gremlin Server {@link Context} object containing settings, request message, etc. * @param itty The result to iterator * @throws TimeoutException if the time taken to serialize the entire result set exceeds the allowable time. */ protected void handleIterator(final Context context, final Iterator itty) throws TimeoutException, InterruptedException { final ChannelHandlerContext ctx = context.getChannelHandlerContext(); final RequestMessage msg = context.getRequestMessage(); final Settings settings = context.getSettings(); final MessageSerializer serializer = ctx.channel().attr(StateKey.SERIALIZER).get(); final boolean useBinary = ctx.channel().attr(StateKey.USE_BINARY).get(); boolean warnOnce = false; // sessionless requests are always transaction managed, but in-session requests are configurable. final boolean managedTransactionsForRequest = manageTransactions ? true : (Boolean) msg.getArgs().getOrDefault(Tokens.ARGS_MANAGE_TRANSACTION, false); // we have an empty iterator - happens on stuff like: g.V().iterate() if (!itty.hasNext()) { // as there is nothing left to iterate if we are transaction managed then we should execute a // commit here before we send back a NO_CONTENT which implies success if (managedTransactionsForRequest) attemptCommit(msg, context.getGraphManager(), settings.strictTransactionManagement); ctx.writeAndFlush(ResponseMessage.build(msg).code(ResponseStatusCode.NO_CONTENT).create()); return; } // timer for the total serialization time final StopWatch stopWatch = new StopWatch(); stopWatch.start(); // the batch size can be overridden by the request final int resultIterationBatchSize = (Integer) msg.optionalArgs(Tokens.ARGS_BATCH_SIZE) .orElse(settings.resultIterationBatchSize); List<Object> aggregate = new ArrayList<>(resultIterationBatchSize); // use an external control to manage the loop as opposed to just checking hasNext() in the while. this // prevent situations where auto transactions create a new transaction after calls to commit() withing // the loop on calls to hasNext(). boolean hasMore = itty.hasNext(); while (hasMore) { if (Thread.interrupted()) throw new InterruptedException(); // have to check the aggregate size because it is possible that the channel is not writeable (below) // so iterating next() if the message is not written and flushed would bump the aggregate size beyond // the expected resultIterationBatchSize. Total serialization time for the response remains in // effect so if the client is "slow" it may simply timeout. if (aggregate.size() < resultIterationBatchSize) aggregate.add(itty.next()); // send back a page of results if batch size is met or if it's the end of the results being iterated. // also check writeability of the channel to prevent OOME for slow clients. if (ctx.channel().isWritable()) { if (aggregate.size() == resultIterationBatchSize || !itty.hasNext()) { final ResponseStatusCode code = itty.hasNext() ? ResponseStatusCode.PARTIAL_CONTENT : ResponseStatusCode.SUCCESS; // serialize here because in sessionless requests the serialization must occur in the same // thread as the eval. as eval occurs in the GremlinExecutor there's no way to get back to the // thread that processed the eval of the script so, we have to push serialization down into that Frame frame; try { frame = makeFrame(ctx, msg, serializer, useBinary, aggregate, code); } catch (Exception ex) { // exception is handled in makeFrame() - serialization error gets written back to driver // at that point if (manageTransactions) attemptRollback(msg, context.getGraphManager(), settings.strictTransactionManagement); break; } // only need to reset the aggregation list if there's more stuff to write if (itty.hasNext()) aggregate = new ArrayList<>(resultIterationBatchSize); else { // iteration and serialization are both complete which means this finished successfully. note that // errors internal to script eval or timeout will rollback given GremlinServer's global configurations. // local errors will get rolledback below because the exceptions aren't thrown in those cases to be // caught by the GremlinExecutor for global rollback logic. this only needs to be committed if // there are no more items to iterate and serialization is complete if (managedTransactionsForRequest) attemptCommit(msg, context.getGraphManager(), settings.strictTransactionManagement); // exit the result iteration loop as there are no more results left. using this external control // because of the above commit. some graphs may open a new transaction on the call to // hasNext() hasMore = false; } // the flush is called after the commit has potentially occurred. in this way, if a commit was // required then it will be 100% complete before the client receives it. the "frame" at this point // should have completely detached objects from the transaction (i.e. serialization has occurred) // so a new one should not be opened on the flush down the netty pipeline ctx.writeAndFlush(frame); } } else { // don't keep triggering this warning over and over again for the same request if (!warnOnce) { logger.warn( "Pausing response writing as writeBufferHighWaterMark exceeded on {} - writing will continue once client has caught up", msg); warnOnce = true; } // since the client is lagging we can hold here for a period of time for the client to catch up. // this isn't blocking the IO thread - just a worker. TimeUnit.MILLISECONDS.sleep(10); } stopWatch.split(); if (stopWatch.getSplitTime() > settings.serializedResponseTimeout) { final String timeoutMsg = String.format( "Serialization of the entire response exceeded the 'serializeResponseTimeout' setting %s", warnOnce ? "[Gremlin Server paused writes to client as messages were not being consumed quickly enough]" : ""); throw new TimeoutException(timeoutMsg.trim()); } stopWatch.unsplit(); } stopWatch.stop(); }
From source file:com.zia.freshdocs.widget.adapter.CMISAdapter.java
/** * Download the content for the given NodeRef * /*from w w w . j av a 2s . c om*/ * @param ref * @param handler */ protected void downloadContent(final NodeRef ref, final Handler handler) { startProgressDlg(false); mProgressDlg.setMax(Long.valueOf(ref.getContentLength()).intValue()); mDlThread = new ChildDownloadThread(handler, new Downloadable() { public Object execute() { File f = null; try { CMISApplication app = (CMISApplication) getContext().getApplicationContext(); URL url = new URL(ref.getContent()); String name = ref.getName(); long fileSize = ref.getContentLength(); f = app.getFile(name, fileSize); if (f != null && f.length() != fileSize) { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); FileOutputStream fos = new FileOutputStream(f); InputStream is = mCmis.get(url.getPath()); byte[] buffer = new byte[BUF_SIZE]; int len = is.read(buffer); int total = len; Message msg = null; Bundle b = null; while (len != -1) { msg = handler.obtainMessage(); b = new Bundle(); b.putInt("progress", total); msg.setData(b); handler.sendMessage(msg); fos.write(buffer, 0, len); len = is.read(buffer); total += len; if (Thread.interrupted()) { fos.close(); f = null; throw new InterruptedException(); } } fos.flush(); fos.close(); } } catch (Exception e) { Log.e(CMISAdapter.class.getSimpleName(), "", e); } return f; } }); mDlThread.start(); }
From source file:com.chinamobile.bcbsp.bspstaff.BSPStaff.java
/** just for test */ public void loadData(BSPJob job) throws ClassNotFoundException, IOException, InterruptedException { int i = 0;//from w ww. j ava 2s.com this.partitioner = (Partitioner<Text>) ReflectionUtils.newInstance( job.getConf().getClass(Constants.USER_BC_BSP_JOB_PARTITIONER_CLASS, HashPartitioner.class), job.getConf()); if (i == 1) { throw new ClassNotFoundException(); } else if (i == 2) { throw new IOException(); } else if (i == 3) { throw new InterruptedException(); } }
From source file:gda.data.scan.datawriter.NexusDataWriter.java
private void checkForThreadInterrupt() throws InterruptedException { if (Thread.interrupted()) { Thread.currentThread().interrupt(); throw new InterruptedException(); }/*from w w w .j a v a 2 s . co m*/ }
From source file:fr.msch.wissl.server.Library.java
private void listFiles(File dir, Queue<File> acc) throws IOException, InterruptedException { if (stop)//from w w w . ja v a 2 s. c o m throw new InterruptedException(); if (!dir.isDirectory()) { throw new IOException(dir.getAbsolutePath() + " is not a directory"); } File[] children = dir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { if (pathname.getAbsolutePath().length() > 254) { return false; } String name = pathname.getName().toLowerCase(); for (String format : Config.getMusicFormats()) { if (name.endsWith(format)) { return true; } } if (pathname.isDirectory()) { return true; } return false; } }); for (File child : children) { if (child.isDirectory()) { listFiles(child, acc); } else { acc.add(child); songsTodo++; } } }