List of usage examples for java.lang Thread interrupt
public void interrupt()
From source file:alluxio.cli.fs.command.DistributedMvCommand.java
@Override public int run(CommandLine cl) throws AlluxioException, IOException { String[] args = cl.getArgs(); AlluxioURI srcPath = new AlluxioURI(args[0]); AlluxioURI dstPath = new AlluxioURI(args[1]); if (mFileSystem.exists(dstPath)) { throw new RuntimeException(dstPath + " already exists"); }/*from w ww . ja v a2 s . com*/ Thread thread = JobThriftClientUtils.createProgressThread(2 * Constants.SECOND_MS, System.out); thread.start(); try { JobThriftClientUtils.run(new MoveConfig(srcPath.getPath(), dstPath.getPath(), null, true), 3); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return -1; } finally { thread.interrupt(); } System.out.println("Moved " + srcPath + " to " + dstPath); return 0; }
From source file:org.jasig.portal.portlet.rendering.worker.PortletExecutionWorker.java
@Override public final void cancel() { if (this.future == null) { throw new IllegalStateException("submit() must be called before cancel() can be called"); }// w w w . j a va 2s . c om if (this.isComplete()) { return; } //Mark worker as retrieved this.retrieved = true; //Notify the guarding req/res wrappers that cancel has been called this.canceled.set(true); //Cancel the future, interrupting the thread this.future.cancel(true); //Track the number of times cancel has been called final int count = this.cancelCount.getAndIncrement(); if (count > 0) { //Since Future.cancel only interrupts the thread on the first call interrupt the thread directly final Thread thread = this.workerThread; if (thread != null) { thread.interrupt(); } } }
From source file:org.apache.tika.parser.mock.MockParserTest.java
@Test public void testInterruptibleSleep() { //Without static initialization of the parser, it can take ~1 second after t.start() //before the parser actually calls parse. This is //just the time it takes to instantiate and call AutoDetectParser, do the detection, etc. //This is not thread creation overhead. ParserRunnable r = new ParserRunnable("sleep_interruptible.xml"); Thread t = new Thread(r); t.start();//from w ww .j av a 2s . c o m long start = new Date().getTime(); try { Thread.sleep(1000); } catch (InterruptedException e) { //swallow } t.interrupt(); try { t.join(10000); } catch (InterruptedException e) { //swallow } long elapsed = new Date().getTime() - start; boolean shortEnough = elapsed < 2000;//the xml file specifies 3000 assertTrue("elapsed (" + elapsed + " millis) was not short enough", shortEnough); }
From source file:byps.http.HActiveMessage.java
public synchronized void cancelMessage() { if (log.isDebugEnabled()) log.debug("cancelMessage(" + messageId); canceled = true;//w ww . j ava 2 s . c o m // Threads might wait in getIncomingStream() this.notifyAll(); Thread thread = workerThread; if (log.isDebugEnabled()) log.debug("worker is still running: " + (thread != null)); if (thread != null) { if (log.isDebugEnabled()) log.debug("interrupt thread=" + thread); thread.interrupt(); // The worker thread will call RequestContext.complete // when it is finished. } else if (rctxtMessage != null) { if (log.isDebugEnabled()) log.debug("assume long-poll, complete response with HTTP 410"); // Assume Longpoll request because a worker thread would have called // getAndRemoveRequestContext // before it has called removeWorker. // This block is executed, if the session is invalidated. // The response code is SC_GONE in order to stop HServerR on the // client side from // sending a new long-poll. HttpServletResponse resp = (HttpServletResponse) rctxtMessage.getResponse(); resp.setStatus(HttpServletResponse.SC_GONE); rctxtMessage.complete(); rctxtMessage = null; } incomingStreams.clear(); checkFinished(); if (log.isDebugEnabled()) log.debug(")cancelMessage"); }
From source file:au.org.intersect.dms.wn.impl.WorkerNodeImpl.java
@Override public boolean stopJob(Long jobId) { boolean resp = false; synchronized (trackers) { JobTracker tracker = trackers.get(jobId); if (tracker != null) { Thread thread = tracker.getThread(); LOGGER.info("Stopping copy thread: " + thread.getName()); thread.interrupt(); resp = true;/*from ww w.jav a 2s .c om*/ } } return resp; }
From source file:org.archive.mapred.ARCMapRunner.java
protected void cleanup(final Thread thread, final ARCReporter reporter) throws IOException { if (!thread.isAlive()) { return;/*from w ww . j ava 2 s . co m*/ } reporter.setStatus("Killing indexing thread " + thread.getName(), true); thread.interrupt(); try { // Give it some time to die. thread.join(1000); } catch (final InterruptedException e) { e.printStackTrace(); } if (thread.isAlive()) { LOG.info(thread.getName() + " will not die"); } }
From source file:bear.plugins.java.JenkinsCache.java
public static File download(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri, String user, String pass) { try {//from w w w. j ava2s. c o m Optional<JDKFile> optional = load(jenkinsCache, jenkinsUri, jdkVersion); if (!optional.isPresent()) { throw new RuntimeException("could not find: " + jdkVersion); } String uri = optional.get().filepath; SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); Scheme httpScheme = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); schemeRegistry.register(httpsScheme); schemeRegistry.register(httpScheme); DefaultHttpClient httpClient = new DefaultHttpClient( new PoolingClientConnectionManager(schemeRegistry)); CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("gpw_e24", "."); cookie.setDomain("oracle.com"); cookie.setPath("/"); cookie.setSecure(true); cookieStore.addCookie(cookie); httpClient.setCookieStore(cookieStore); HttpPost httppost = new HttpPost("https://login.oracle.com"); httppost.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8")); HttpResponse response = httpClient.execute(httppost); int code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("unable to auth: " + code); } // closes the single connection // EntityUtils.consumeQuietly(response.getEntity()); httppost = new HttpPost(uri); httppost.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8")); response = httpClient.execute(httppost); code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("to download: " + uri); } File file = new File(tempDestDir, optional.get().name); HttpEntity entity = response.getEntity(); final long length = entity.getContentLength(); final CountingOutputStream os = new CountingOutputStream(new FileOutputStream(file)); System.out.printf("Downloading %s to %s...%n", uri, file); Thread progressThread = new Thread(new Runnable() { double lastProgress; @Override public void run() { while (!Thread.currentThread().isInterrupted()) { long copied = os.getCount(); double progress = copied * 100D / length; if (progress != lastProgress) { System.out.printf("\rProgress: %s%%", LangUtils.toConciseString(progress, 1)); } lastProgress = progress; try { Thread.sleep(500); } catch (InterruptedException e) { break; } } } }, "progressThread"); progressThread.start(); ByteStreams.copy(entity.getContent(), os); progressThread.interrupt(); System.out.println("Download complete."); return file; } catch (Exception e) { throw Exceptions.runtime(e); } }
From source file:bear.plugins.java.JenkinsCache.java
public static File download2(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri, String user, String pass) { try {/* w w w.j ava2 s . co m*/ Optional<JDKFile> optional = load(jenkinsCache, jenkinsUri, jdkVersion); if (!optional.isPresent()) { throw new RuntimeException("could not find: " + jdkVersion); } String uri = optional.get().filepath; // agent.get() // agent.get() SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); DefaultHttpClient httpClient = new DefaultHttpClient( new PoolingClientConnectionManager(schemeRegistry)); MechanizeAgent agent = new MechanizeAgent(); Cookie cookie2 = agent.cookies().addNewCookie("gpw_e24", ".", "oracle.com"); cookie2.getHttpCookie().setPath("/"); cookie2.getHttpCookie().setSecure(false); CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("gpw_e24", "."); cookie.setDomain("oracle.com"); cookie.setPath("/"); cookie.setSecure(true); cookieStore.addCookie(cookie); httpClient.setCookieStore(cookieStore); HttpPost httppost = new HttpPost("https://login.oracle.com"); httppost.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8")); HttpResponse response = httpClient.execute(httppost); int code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("unable to auth: " + code); } // EntityUtils.consumeQuietly(response.getEntity()); httppost = new HttpPost(uri); response = httpClient.execute(httppost); code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("to download: " + uri); } File file = new File(tempDestDir, optional.get().name); HttpEntity entity = response.getEntity(); final long length = entity.getContentLength(); final CountingOutputStream os = new CountingOutputStream(new FileOutputStream(file)); System.out.printf("Downloading %s to %s...%n", uri, file); Thread progressThread = new Thread(new Runnable() { double lastProgress; @Override public void run() { while (!Thread.currentThread().isInterrupted()) { long copied = os.getCount(); double progress = copied * 100D / length; if (progress != lastProgress) { System.out.printf("\rProgress: %s%%", LangUtils.toConciseString(progress, 1)); } lastProgress = progress; try { Thread.sleep(500); } catch (InterruptedException e) { break; } } } }, "progressThread"); progressThread.start(); ByteStreams.copy(entity.getContent(), os); progressThread.interrupt(); System.out.println("Download complete."); return file; } catch (Exception e) { throw Exceptions.runtime(e); } }
From source file:uk.ac.kcl.tika.parsers.PDFPreprocessorParser.java
private File makeTiffFromPDF(File input, File output, ImageMagickConfig config) throws IOException, TikaException { String[] cmd = { config.getImageMagickPath() + getImageMagickProg(), "-density", config.getDensity(), input.getPath(), "-depth", config.getDepth(), "-quality", config.getQuality(), output.getPath() }; ProcessBuilder pb = new ProcessBuilder(cmd); //setEnv(config, pb); final Process process = pb.start(); process.getOutputStream().close();// ww w .j a v a 2 s . co m InputStream out = process.getInputStream(); InputStream err = process.getErrorStream(); logStream("IMAGEMAGICK MSG", out, input); logStream("IMAGEMAGICK ERROR", err, input); FutureTask<Integer> waitTask = new FutureTask<Integer>(new Callable<Integer>() { public Integer call() throws Exception { return process.waitFor(); } }); Thread waitThread = new Thread(waitTask); waitThread.start(); try { waitTask.get(config.getTimeout(), TimeUnit.SECONDS); return output; } catch (InterruptedException e) { waitThread.interrupt(); process.destroy(); Thread.currentThread().interrupt(); throw new TikaException("ImageMagickOCRPDFParser interrupted", e); } catch (ExecutionException e) { // should not be thrown } catch (TimeoutException e) { waitThread.interrupt(); process.destroy(); throw new TikaException("ImageMagickOCRPDFParser timeout", e); } return null; }
From source file:Main.java
public ThreadGroupDemo() { MyThreadGroup pGroup = new MyThreadGroup("ParentThreadGroup"); MyThreadGroup cGroup = new MyThreadGroup(pGroup, "ChildThreadGroup"); Thread thr2 = new Thread(pGroup, this); System.out.println("Starting " + thr2.getName()); thr2.start();/*from w w w .j a v a 2 s. c o m*/ // create third thread Thread thr3 = new Thread(cGroup, this); System.out.println("Starting " + thr3.getName()); thr3.start(); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } thr2.interrupt(); thr3.interrupt(); }