Example usage for java.lang Thread interrupted

List of usage examples for java.lang Thread interrupted

Introduction

In this page you can find the example usage for java.lang Thread interrupted.

Prototype

public static boolean interrupted() 

Source Link

Document

Tests whether the current thread has been interrupted.

Usage

From source file:net.sourceforge.vulcan.ant.AntBuildToolTestBase.java

@Override
protected void setUp() throws Exception {
    antConfig = new AntConfig();
    antConfig.setAntHome(antHome);//from  w  ww. j a  v a  2  s. co m
    config = new AntProjectConfig();
    config.setTargets("clean compile");

    javaEnvironment = new JavaHome();
    javaEnvironment.setJavaHome(System.getProperty("java.home"));

    eventSource = new UdpEventSource();

    if (addCoberturaRuntimeIfEnabled) {
        configureCobertura();
    }

    tool = new AntBuildTool(config, antConfig, javaEnvironment, eventSource);

    projectConfig = new ProjectConfigDto();
    projectConfig.setWorkDir(TestUtils.resolveRelativePath("source/test/workdir"));

    if (StringUtils.isBlank(antHome) || !(new File(antHome)).isDirectory()) {
        fail("Please define ant.home in build.properties");
    }

    // clear any pending interrupts
    Thread.interrupted();
}

From source file:org.apache.hadoop.hdfs.LeaseRenewal.java

@Override
public void run() {
    long lastRenewed = 0;
    int retries = 0;
    long renewal = computeRenewalPeriod();
    int maxRetries = conf.getInt("dfs.lease.renewal.retries", FSConstants.MAX_LEASE_RENEWAL_RETRIES);
    while (running && !Thread.interrupted()) {
        if (System.currentTimeMillis() - lastRenewed > renewal) {
            try {
                renew();/*www. j a v  a 2s .  c  om*/
                lastRenewed = System.currentTimeMillis();
                retries = 0;
            } catch (SocketException ie) {
                retries++;
                LOG.warn("Can't renew lease for " + clientName + " for a period of " + (renewal / 1000)
                        + " seconds because NameNode is not reachable. Retried " + retries + " out of "
                        + maxRetries, ie);
                if (retries > maxRetries) {
                    LOG.warn("Can't renew lease for " + clientName + " for a period of " + (renewal / 1000)
                            + " seconds because NameNode is not reachable. Shutting down HDFS client...", ie);
                    abort();
                    break;
                }
            } catch (IOException ie) {
                LOG.warn("Problem renewing lease for " + clientName + " for a period of " + (renewal / 1000)
                        + " seconds. Will retry shortly...", ie);
            }
        }
        renewalSleep();
    }
}

From source file:org.apache.drill.test.DrillTest.java

@AfterClass
public static void finiDrillTest() throws InterruptedException {
    testReporter.info(String.format("Test Class done (%s): %s.", memWatcher.getMemString(true), className));
    // Clear interrupts for next test
    Thread.interrupted();
}

From source file:com.github.michalbednarski.intentslab.browser.ApplicationFetcher.java

@Override
Object getEntries(Context context) {
    PackageManager pm = context.getPackageManager();
    int requestedPackageInfoFlags = PackageManager.GET_DISABLED_COMPONENTS
            | (requireMetaDataSubstring != null ? PackageManager.GET_META_DATA : 0);

    List<PackageInfo> allPackages = pm.getInstalledPackages(requestedPackageInfoFlags);

    ArrayList<Component> selectedApps = new ArrayList<Component>();

    for (PackageInfo pack : allPackages) {
        ApplicationInfo applicationInfo = pack.applicationInfo;

        // Filter out non-applications
        if (applicationInfo == null) {
            continue;
        }/*from w  w  w.  j  av a  2  s  . com*/

        // System app filter
        if ((((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? APP_TYPE_SYSTEM : APP_TYPE_USER)
                & appType) == 0) {
            continue;
        }

        // Metadata filter
        if (!checkMetaDataFilter(applicationInfo)) {
            continue;
        }

        // Build and add app descriptor
        Component app = new Component();
        app.title = String.valueOf(applicationInfo.loadLabel(pm));
        app.subtitle = pack.packageName;
        app.componentInfo = applicationInfo;
        selectedApps.add(app);

        // Allow cancelling task
        if (Thread.interrupted()) {
            return null;
        }
    }
    return selectedApps.toArray(new Component[selectedApps.size()]);
}

From source file:de.sjka.logstash.osgi.internal.LogstashSender.java

@Override
public void run() {
    System.out.println("Logstash sender started");
    try {//w  w w  .j  av a2s. co m
        while (true) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }
            LogEntry entry = queue.takeFirst();
            try {
                process(entry);
            } catch (Exception e) {
                queue.putFirst(entry);
                Thread.sleep(60 * SECONDS);
            }
        }
    } catch (InterruptedException e) {
        // all good
    }
    System.out.println("Logstash sender shutting down");
}

From source file:itdelatrisu.opsu.downloads.BloodcatServer.java

/**
 * Returns a JSON object from a URL.//www. j ava2s  . c  om
 * @param url the remote URL
 * @return the JSON object
 * @author Roland Illig (http://stackoverflow.com/a/4308662)
 */
public static JSONObject readJsonFromUrl(URL url) throws IOException {
    // open connection
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(Download.CONNECTION_TIMEOUT);
    conn.setReadTimeout(Download.READ_TIMEOUT);
    conn.setUseCaches(false);
    try {
        conn.connect();
    } catch (SocketTimeoutException e) {
        ErrorHandler.error("Connection to server timed out.", e, false);
        throw e;
    }

    if (Thread.interrupted())
        return null;

    // read JSON
    JSONObject json = null;
    try (InputStream in = conn.getInputStream()) {
        BufferedReader rd = new BufferedReader(new InputStreamReader(in));
        StringBuilder sb = new StringBuilder();
        int c;
        while ((c = rd.read()) != -1)
            sb.append((char) c);
        json = new JSONObject(sb.toString());
    } catch (SocketTimeoutException e) {
        ErrorHandler.error("Connection to server timed out.", e, false);
        throw e;
    } catch (JSONException e1) {
        ErrorHandler.error("Failed to create JSON object.", e1, true);
    }
    return json;
}

From source file:com.all.services.ServiceMonitor.java

public static void main(String[] args) {
    try {/*from  w w w. ja  v a  2s. c om*/
        LOG.info("Starting JMX...");
        runMonitor(ManagementFactory.getPlatformMBeanServer(), "com.all.services:type=ServiceMonitor",
                new ServiceMonitor(Thread.currentThread()));
        while (!Thread.interrupted()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    } catch (Exception e) {
        LOG.error(e, e);
    } finally {
        LOG.info("JMX has stopped.");
        System.exit(0);
    }
}

From source file:eu.rethink.lhcb.client.android.LHCBClientAndroid.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_lhcb_client_android);
    lhcbClient = new LHCBClient();

    // setup ConnectivityMonitorAndroid
    final ConnectivityMonitor cmInstance = new ConnectivityMonitorAndroid(getApplicationContext());
    //cmInstance.startRunner();
    lhcbClient.setConnectivityMonitorInstance(cmInstance);
    lhcbClient.setExtendedDevice(new ExtendedDeviceAndroid(getApplicationContext()));

    // --- get layout elements ---
    // Broker IP/*from   ww w  .  j  a  v  a  2 s.  c om*/
    final EditText brokerIp = (EditText) findViewById(R.id.broker_ip);

    // Broker Port
    final EditText brokerPort = (EditText) findViewById(R.id.broker_port);

    // Client Name
    final EditText clientName = (EditText) findViewById(R.id.client_name);

    // connection state TextView
    final TextView conMonState = (TextView) findViewById(R.id.conmonstate);

    // thread that updates connection state
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            Random r = new Random();
            try {
                while (!Thread.interrupted()) {
                    //final String text = String.valueOf(r.nextInt());
                    final String text = cmInstance.toJson();
                    //LOG.debug("setting text: {}", text);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            conMonState.setText(text);
                        }
                    });
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                //e.printStackTrace();
            }
        }
    });
    t.start();

    // switch that starts and stops the LHCB Client
    switchBtn = (Switch) findViewById(R.id.connect_switch);
    switchBtn.setOnCheckedChangeListener((buttonView, isChecked) -> {
        if (isChecked) {
            //buttonView.setText("connected");
            lhcbClient.setServerHost(brokerIp.getText().toString());
            lhcbClient.setServerPort(Integer.parseInt(brokerPort.getText().toString()));
            lhcbClient.setName(clientName.getText().toString());
            InputStream inputStream = getResources().openRawResource(R.raw.keystore);
            try {
                LOG.debug("Trying to load BKS KeyStore");
                KeyStore bks = KeyStore.getInstance("BKS");
                bks.load(inputStream, "fraunhofer".toCharArray());
                lhcbClient.setKeyStore(bks);
            } catch (KeyStoreException e) {
                e.printStackTrace();
            } catch (CertificateException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            lhcbClient.start();
            //
        } else {
            stopClient();
        }
    });

    int permissionCheck1 = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
    int permissionCheck2 = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

    LOG.info("permissionCheck1: {}", permissionCheck1);
    LOG.info("permissionCheck2: {}", permissionCheck2);
    LOG.info("needed Value: {}", PackageManager.PERMISSION_GRANTED);
    if (permissionCheck1 != PackageManager.PERMISSION_GRANTED
            || permissionCheck2 != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.READ_PHONE_STATE }, 1337);
    }
}

From source file:org.apache.hadoop.hbase.index.write.TestParalleIndexWriter.java

@SuppressWarnings("unchecked")
@Test/*  ww w.  j  a va 2  s .c om*/
public void testSynchronouslyCompletesAllWrites() throws Exception {
    LOG.info("Starting " + test.getTableNameString());
    LOG.info("Current thread is interrupted: " + Thread.interrupted());
    Abortable abort = new StubAbortable();
    Stoppable stop = Mockito.mock(Stoppable.class);
    ExecutorService exec = Executors.newFixedThreadPool(1);
    Map<ImmutableBytesPtr, HTableInterface> tables = new HashMap<ImmutableBytesPtr, HTableInterface>();
    FakeTableFactory factory = new FakeTableFactory(tables);

    ImmutableBytesPtr tableName = new ImmutableBytesPtr(this.test.getTableName());
    Put m = new Put(row);
    m.add(Bytes.toBytes("family"), Bytes.toBytes("qual"), null);
    Multimap<HTableInterfaceReference, Mutation> indexUpdates = ArrayListMultimap
            .<HTableInterfaceReference, Mutation>create();
    indexUpdates.put(new HTableInterfaceReference(tableName), m);

    HTableInterface table = Mockito.mock(HTableInterface.class);
    final boolean[] completed = new boolean[] { false };
    Mockito.when(table.batch(Mockito.anyList())).thenAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            // just keep track that it was called
            completed[0] = true;
            return null;
        }
    });
    Mockito.when(table.getTableName()).thenReturn(test.getTableName());
    // add the table to the set of tables, so its returned to the writer
    tables.put(tableName, table);

    // setup the writer and failure policy
    ParallelWriterIndexCommitter writer = new ParallelWriterIndexCommitter();
    writer.setup(factory, exec, abort, stop, 1);
    writer.write(indexUpdates);
    assertTrue("Writer returned before the table batch completed! Likely a race condition tripped",
            completed[0]);
    writer.stop(this.test.getTableNameString() + " finished");
    assertTrue("Factory didn't get shutdown after writer#stop!", factory.shutdown);
    assertTrue("ExectorService isn't terminated after writer#stop!", exec.isShutdown());
}

From source file:com.delphix.appliance.logger.Logger.java

/**
 * Log the message unequivocally./*from  w  ww . ja  v  a  2  s .  c o  m*/
 */
private void forcedLog(Level level, String message, Throwable t) {
    /*
     * logger4j.callAppenders() will eat the interrupted status, so we clear the status here and restore it after
     * the logger call has completed.
     */
    boolean isInterrupted = Thread.interrupted();

    // The class name (FQCN) lets it know that the caller of this class is the one that should be printed in
    // the log message.  Otherwise the log messages would all say "com.delphix.appliance.logger.Logger..."
    logger4j.callAppenders(new LoggingEvent(LOGGER_FQCN, logger4j, level, message, t));

    if (isInterrupted)
        Thread.currentThread().interrupt();
}