List of usage examples for java.lang Thread interrupted
public static boolean interrupted()
From source file:org.devtcg.five.util.streaming.LocalHttpServer.java
public void run() { if (mReqHandler == null) throw new IllegalStateException("Request handler not set."); if (mSocket == null) throw new IllegalStateException("Not bound."); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); while (Thread.interrupted() == false) { try {/*from w w w.j av a2 s .c o m*/ Socket sock = mSocket.accept(); DefaultHttpServerConnection conn = new DefaultHttpServerConnection(); conn.bind(sock, mParams); BasicHttpProcessor proc = new BasicHttpProcessor(); proc.addInterceptor(new ResponseContent()); proc.addInterceptor(new ResponseConnControl()); HttpRequestHandlerRegistry reg = new HttpRequestHandlerRegistry(); reg.register("*", mReqHandler); HttpService svc = new HttpService(proc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory()); svc.setParams(mParams); svc.setHandlerResolver(reg); WorkerThread t; synchronized (mWorkers) { t = new WorkerThread(svc, conn); mWorkers.add(t); } t.setDaemon(true); t.start(); } catch (IOException e) { Log.e(TAG, "I/O error initializing connection thread: " + e.getMessage()); break; } } }
From source file:com.arpnetworking.tsdcore.sinks.LimitingSink.java
/** * {@inheritDoc}// ww w. j a va2 s. com */ @Override public void close() { _sink.close(); try { _executor.shutdown(); _executor.awaitTermination(EXECUTOR_TIMEOUT_IN_SECONDS, TimeUnit.SECONDS); } catch (final InterruptedException e) { Thread.interrupted(); Throwables.propagate(e); } flushMetrics(); }
From source file:com.beetle.framework.util.OtherUtil.java
/** * ?sleep?object.wait// w w w . j ava 2s . c o m * * @param lockObj * ? * @param sometime * ?? * @throws InterruptedException */ public static final void blockSomeTime(final Object lockObj, long sometime) throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); synchronized (lockObj) { long waitTime = sometime; long start = System.currentTimeMillis(); try { for (;;) { lockObj.wait(waitTime); waitTime = sometime - (System.currentTimeMillis() - start); if (waitTime <= 0) { break; } } } catch (InterruptedException ex) { lockObj.notify(); throw ex; } } }
From source file:org.cyclop.service.importer.intern.ParallelQueryImporter.java
private void waitForImport(List<Future<Void>> futures) { LOG.debug("Tasks submitted - waiting for results"); for (Future<Void> future : futures) { try {/*from w ww. j a va2s . c o m*/ future.get(); } catch (InterruptedException e) { Thread.interrupted(); LOG.warn("Import executor interrupted", e); } catch (Exception e) { LOG.error("Import executor error", e); } } }
From source file:edu.umich.robot.soar.Soar.java
public Soar(Config config) { data = new SoarDataCollector(clock, properties, config); // kernel = Kernel.CreateKernelInNewThread(Kernel.kUseAnyPort); kernel = Kernel.CreateKernelInNewThread(); if (kernel.HadError()) throw new IllegalStateException("Soar error: " + kernel.GetLastErrorDescription()); int port = kernel.GetListenerPort(); while (port == -1) { try {/*from ww w. j a v a 2 s .c o m*/ Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } port = kernel.GetListenerPort(); } System.out.println("Started Soar kernel on port: " + port); kernel.SetAutoCommit(false); kernel.SetTraceCommunications(false); kernel.RegisterForUpdateEvent(smlUpdateEventId.smlEVENT_AFTER_ALL_OUTPUT_PHASES, new UpdateEventInterface() { public void updateEventHandler(int eventID, Object d, Kernel kernel, int arg3) { logger.trace("smlEVENT_AFTER_ALL_OUTPUT_PHASES"); if (Thread.interrupted()) { logger.debug("Stopping Soar"); kernel.StopAllAgents(); } for (SoarAgent agent : agents) agent.update(); data.incrementDecisionCycle(); if (data.shouldCollectData()) for (SoarAgent agent : agents) data.collect(agent); logger.trace("smlEVENT_AFTER_ALL_OUTPUT_PHASES done"); } }, null); kernel.RegisterForSystemEvent(smlSystemEventId.smlEVENT_SYSTEM_START, systemHandler, null); kernel.RegisterForSystemEvent(smlSystemEventId.smlEVENT_SYSTEM_STOP, systemHandler, null); kernel.RegisterForAgentEvent(smlAgentEventId.smlEVENT_AFTER_AGENT_REINITIALIZED, agentHandler, null); }
From source file:org.ulyssis.ipp.control.CommandDispatcher.java
public void run() { Thread statusThread = new Thread(() -> { try {/* w w w. j a v a2 s. c o m*/ while (!Thread.currentThread().isInterrupted()) { try { JedisHelper.get(redisUri).subscribe(createResultListener(), statusChannel); } catch (JedisConnectionException e) { // TODO: After a while, deregister the processor? LOG.error("Connection with Redis was broken! Trying again in 0.5s.", e); Thread.sleep(500L); } } } catch (InterruptedException ignored) { } }); statusThread.start(); while (!Thread.interrupted()) { try { Command command = commandsToSend.take(); LOG.debug("Sending command {}", command.getCommandId()); jedis.publish(controlChannel, Serialization.getJsonMapper().writeValueAsBytes(command)); } catch (InterruptedException ignored) { } catch (JsonProcessingException e) { LOG.error("Error writing command as JSON object", e); } } statusThread.interrupt(); try { statusThread.join(); } catch (InterruptedException ignored) { } }
From source file:net.sourceforge.vulcan.maven.MavenBuildToolTestBase.java
@Override protected void setUp() throws Exception { mavenConfig = new MavenConfig(); final MavenHome[] homes = new MavenHome[] { new MavenHome(), new MavenHome() }; homes[0].setDescription("maven one-x"); homes[0].setDirectory(mavenHome);// w ww .j av a 2s .c o m homes[1].setDescription("maven two"); homes[1].setDirectory(maven2Home); mavenConfig.setMavenHomes(homes); config = new MavenProjectConfig(); config.setTargets("clean"); config.setBuildScript(""); config.setOffline(true); int index = 0; if (useMaven2) { index = 1; } tool = new MavenBuildTool(config, mavenConfig, null, mavenConfig.getMavenHomes()[index]) { @Override protected void buildProjectInternal(ProjectConfigDto projectConfig, ProjectStatusDto status, File logFile, BuildDetailCallback callback) throws BuildFailedException, ConfigException { MavenBuildToolTestBase.this.foreheadFile = this.launchConfigFile; assertTrue(launchConfigFile.exists()); assertTrue(launchConfigFile.length() > 0); throw new TokenException(); } }; projectConfig = new ProjectConfigDto(); projectConfig.setWorkDir(TestUtils.resolveRelativePath("source/test/workdir")); if (StringUtils.isBlank(mavenHome) || !(new File(mavenHome)).isDirectory()) { fail("Please define maven1.home and maven2.home in build.properties"); } // clear any pending interrupts Thread.interrupted(); }
From source file:org.apache.hadoop.hbase.master.ZKClusterStateRecovery.java
/** * Register live regionservers that we read from ZK with ServerManager. We do this after starting * RPC threads but before log splitting. *//*from ww w . j av a2 s. co m*/ void registerLiveRegionServers() throws IOException { liveRSNamesAtStartup = zkw.getLiveRSNames(); liveRSNamesAtStartupUnmodifiable = Collections.unmodifiableSet(liveRSNamesAtStartup); Set<String> rsNamesToAdd = new TreeSet<String>(liveRSNamesAtStartup); boolean needToSleep = false; // no need to sleep at the first iteration while (!rsNamesToAdd.isEmpty()) { if (needToSleep) { Threads.sleepRetainInterrupt(HConstants.SOCKET_RETRY_WAIT_MS); } // We cannot modify rsNamesToAdd as we iterate it, so we add RS names to retry to this list. Set<String> rsLeftToAdd = new TreeSet<String>(); for (String rsName : rsNamesToAdd) { if (master.isStopped()) { throw new IOException("Master is shutting down"); } if (Thread.interrupted()) { throw new IOException("Interrupted when scanning live RS directory in ZK"); } HServerInfo serverInfo; try { serverInfo = HServerInfo.fromServerName(rsName); } catch (IllegalArgumentException ex) { // This error is probably not going to fix itself automatically. Exit the retry loop. throw new IOException("Read invalid server name for live RS directory in ZK: " + rsName, ex); } try { serverManager.recordNewServer(serverInfo); } catch (IOException ex) { if (ex.getCause() instanceof NoNodeException) { // This regionserver has disappeared, don't try to register it. This will also ensure // that we split the logs for this regionserver as part of initial log splitting. LOG.info("Regionserver znode " + rsName + " disappeared, not registering"); liveRSNamesAtStartup.remove(rsName); } else { LOG.error("Error recording a new regionserver: " + serverInfo.getServerName() + ", will retry", ex); rsLeftToAdd.add(rsName); } } } rsNamesToAdd = rsLeftToAdd; needToSleep = true; // will sleep before the re-trying } }
From source file:net.iponweb.hadoop.streaming.parquet.TextRecordWriterWrapper.java
@Override public void close(Reporter reporter) throws IOException { try {//from w w w . j ava 2 s . co m realWriter.close(null); } catch (InterruptedException e) { Thread.interrupted(); throw new IOException(e); } }
From source file:org.apache.tomee.jul.handler.rotating.ArchivingTest.java
@Test public void logAndRotate() throws IOException, NoSuchMethodException { clean("target/ArchivingTest-" + format + "/logs"); final AtomicReference<String> today = new AtomicReference<>(); final Map<String, String> config = new HashMap<>(); // initial config today.set("2015-09-01"); config.put("filenamePattern", "target/ArchivingTest-" + format + "/logs/test.%s.%d.log"); config.put("archiveDirectory", "target/ArchivingTest-" + format + "/logs/archives"); config.put("archiveFormat", format); config.put("archiveOlderThan", "1 s"); config.put("limit", "10 kilobytes"); config.put("level", "INFO"); config.put("dateCheckInterval", "1 second"); final LocalFileHandler handler = new LocalFileHandler() { @Override/*from www.j av a2 s . com*/ protected String currentDate() { return today.get(); } @Override protected String getProperty(final String name, final String defaultValue) { final String s = config.get(name.substring(name.lastIndexOf('.') + 1)); return s != null ? s : defaultValue; } }; final String string10chars = "abcdefghij"; final int iterations = 950; for (int i = 0; i < iterations; i++) { handler.publish(new LogRecord(Level.INFO, string10chars)); } today.set("2015-09-02"); try { // ensure we test the date Thread.sleep(2000); } catch (final InterruptedException e) { Thread.interrupted(); } handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the archiving handler.close(); withRetry(10, 3, new Runnable() { @Override public void run() { final File logGzip = new File( "target/ArchivingTest-" + format + "/logs/archives/test.2015-09-01.0.log." + format); assertTrue(logGzip.getAbsolutePath(), logGzip.isFile()); } }); // note: size depends on the date so just use a > min if ("gzip".equals(format)) { try (final GZIPInputStream gis = new GZIPInputStream( new FileInputStream("target/ArchivingTest-gzip/logs/archives/test.2015-09-01.0.log.gzip"))) { final String content = IOUtils.toString(gis); assertTrue( content.contains(Level.INFO.getLocalizedName() + ": abcdefghij" + System.lineSeparator())); assertTrue(content.length() > 10000); } } else { try (final ZipInputStream zis = new ZipInputStream( new FileInputStream("target/ArchivingTest-zip/logs/archives/test.2015-09-01.0.log.zip"))) { assertEquals("test.2015-09-01.0.log", zis.getNextEntry().getName()); final String content = IOUtils.toString(zis); assertTrue(content, content.contains(Level.INFO.getLocalizedName() + ": abcdefghij" + System.lineSeparator())); // INFO or INFOS assertTrue(content, content.length() > 10000); assertNull(zis.getNextEntry()); } } }