Example usage for java.lang Thread interrupt

List of usage examples for java.lang Thread interrupt

Introduction

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

Prototype

public void interrupt() 

Source Link

Document

Interrupts this thread.

Usage

From source file:org.apache.hadoop.hbase.regionserver.wal.TestLogRollPeriod.java

/**
 * Tests that the LogRoller perform the roll with some data in the log
 *//*from  ww w.ja  va 2s. c  om*/
@Test(timeout = 60000)
public void testWithEdits() throws Exception {
    final String tableName = "TestLogRollPeriodWithEdits";
    final String family = "cf";

    TEST_UTIL.createTable(tableName, family);
    try {
        HRegionServer server = TEST_UTIL.getRSForFirstRegionInTable(Bytes.toBytes(tableName));
        HLog log = server.getWAL();
        final HTable table = new HTable(TEST_UTIL.getConfiguration(), tableName);

        Thread writerThread = new Thread("writer") {
            @Override
            public void run() {
                try {
                    long row = 0;
                    while (!interrupted()) {
                        Put p = new Put(Bytes.toBytes(String.format("row%d", row)));
                        p.add(Bytes.toBytes(family), Bytes.toBytes("col"), Bytes.toBytes(row));
                        table.put(p);
                        row++;

                        Thread.sleep(LOG_ROLL_PERIOD / 16);
                    }
                } catch (Exception e) {
                    LOG.warn(e);
                }
            }
        };

        try {
            writerThread.start();
            checkMinLogRolls(log, 5);
        } finally {
            writerThread.interrupt();
            writerThread.join();
            table.close();
        }
    } finally {
        TEST_UTIL.deleteTable(tableName);
    }
}

From source file:org.energy_home.jemma.internal.device.zgd.StreamGobbler.java

private void stopProcess() {
    // atomic because pollingThread is volatile
    Thread tmpThread = processThread;

    processThread = null;//from w ww. ja va 2  s .  c om

    if (tmpThread != null) {
        tmpThread.interrupt();
        try {
            tmpThread.join();
        } catch (InterruptedException e) {
            log.error(e);
        }
    }

    if (log != null)
        log.debug("stopped process");
}

From source file:org.silverpeas.core.util.DBUtilIntegrationTest.java

@Test
public void nextUniqueIdUpdateForAnExistingTableShouldWorkInRequiredTransaction() throws Exception {
    assertThat(actualMaxIdInUniqueIdFor("User"), is(1));
    final Thread nextIdThread = new Thread(() -> {
        try {/*from  www .j  av  a  2 s.  co m*/
            Transaction.performInOne(() -> {
                int nextId = 0;
                nextId = DBUtil.getNextId("User", "id");
                assertThat(actualMaxIdInUniqueIdFor("User"), is(nextId));
                assertThat(nextId, is(2));
                return null;
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    });

    try {
        assertThat(actualMaxIdInUniqueIdFor("User"), is(1));
        nextIdThread.start();
        nextIdThread.join();
        assertThat(actualMaxIdInUniqueIdFor("User"), is(2));
    } finally {
        nextIdThread.interrupt();
    }
}

From source file:org.kchine.rpf.PoolUtils.java

public static void die(final ManagedServant servant, long dieTimeOut) throws RemoteException {
    final Object[] resultHolder = new Object[1];
    Runnable dieRunnable = new Runnable() {
        public void run() {
            try {
                servant.die();/*  www .j a  va2  s  . com*/
                resultHolder[0] = DIE_DONE;
            } catch (UnmarshalException ue) {
                resultHolder[0] = DIE_DONE;
            } catch (Exception e) {
                final boolean wasInterrupted = Thread.interrupted();
                if (wasInterrupted) {
                    resultHolder[0] = new DieInterrupted();
                } else {
                    resultHolder[0] = e;
                }
            }
        }
    };

    Thread dieThread = InterruptibleRMIThreadFactory.getInstance().newThread(dieRunnable);
    dieThread.start();

    long t1 = System.currentTimeMillis();
    while (resultHolder[0] == null) {
        if ((System.currentTimeMillis() - t1) > dieTimeOut) {
            dieThread.interrupt();
            resultHolder[0] = new DieTimeout();
            break;
        }
        try {
            Thread.sleep(10);
        } catch (Exception e) {
        }
    }

    if (resultHolder[0] instanceof Throwable) {
        throw (RemoteException) resultHolder[0];
    }
}

From source file:fm.smart.r1.activity.CreateItemActivity.java

public void onClick(View v) {
    EditText cueInput = (EditText) findViewById(R.id.cue);
    EditText responseInput = (EditText) findViewById(R.id.response);
    Spinner posInput = (Spinner) findViewById(R.id.pos);
    EditText characterResponseInput = (EditText) findViewById(R.id.response_character);
    EditText characterCueInput = (EditText) findViewById(R.id.cue_character);
    final String cue = cueInput.getText().toString();
    final String response = responseInput.getText().toString();
    final String pos = posInput.getSelectedItem().toString();
    final String character_cue = characterCueInput.getText().toString();
    final String character_response = characterResponseInput.getText().toString();
    String pos_code = Utils.POS_MAP.get(pos);
    if (TextUtils.isEmpty(pos_code)) {
        pos_code = "NONE";
    }/* w w  w .  j ava2s .c  o  m*/
    final String final_pos_code = pos_code;

    if (Main.isNotLoggedIn(this)) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setClassName(this, LoginActivity.class.getName());
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); // avoid
        // navigation
        // back to this?
        LoginActivity.return_to = CreateItemActivity.class.getName();
        LoginActivity.params = new HashMap<String, String>();
        LoginActivity.params.put("list_id", list_id);
        LoginActivity.params.put("cue", cue);
        LoginActivity.params.put("response", response);
        LoginActivity.params.put("cue_language", cue_language);
        LoginActivity.params.put("response_language", response_language);
        LoginActivity.params.put("pos", pos);
        LoginActivity.params.put("character_cue", character_cue);
        LoginActivity.params.put("character_response", character_response);
        startActivity(intent);
    } else {
        // TODO cue and response languages need to be inferred from list we are
        // adding to ... Might want to fix those, i.e. not allow variation
        // on
        // search ...
        // TODO wondering whether there is some way to edit existing items
        // ...

        final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
        myOtherProgressDialog.setTitle("Please Wait ...");
        myOtherProgressDialog.setMessage("Creating Item ...");
        myOtherProgressDialog.setIndeterminate(true);
        myOtherProgressDialog.setCancelable(true);

        final Thread create_item = new Thread() {
            public void run() {
                // TODO make this interruptable .../*if
                // (!this.isInterrupted())*/
                CreateItemActivity.create_item_result = createItem(cue, cue_language, character_cue,
                        final_pos_code, response, response_language, character_response, list_id);

                myOtherProgressDialog.dismiss();

            }
        };
        myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                create_item.interrupt();
            }
        });
        OnCancelListener ocl = new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                create_item.interrupt();
            }
        };
        myOtherProgressDialog.setOnCancelListener(ocl);
        myOtherProgressDialog.show();
        create_item.start();
    }
}

From source file:maker.task.compile.ReplTestPumpStreamHandler.java

/**
 * Stopping a pumper thread. The implementation actually waits
 * longer than specified in 'timeout' to detect if the timeout
 * was indeed exceeded. If the timeout was exceeded an IOException
 * is created to be thrown to the caller.
 *
 * @param thread  the thread to be stopped
 * @param timeout the time in ms to wait to join
 *///  w w  w .  j  a v a 2 s. c  o m
protected void stopThread(final Thread thread, final long timeout) {

    if (thread != null) {
        try {
            if (timeout == 0) {
                thread.join();
            } else {
                final long timeToWait = timeout + STOP_TIMEOUT_ADDITION;
                final long startTime = System.currentTimeMillis();
                thread.join(timeToWait);
                if (!(System.currentTimeMillis() < startTime + timeToWait)) {
                    final String msg = "The stop timeout of " + timeout + " ms was exceeded";
                    caught = new ExecuteException(msg, Executor.INVALID_EXITVALUE);
                }
            }
        } catch (final InterruptedException e) {
            thread.interrupt();
        }
    }
}

From source file:org.kchine.rpf.PoolUtils.java

public static void ping(final ManagedServant servant, long pingTimeOut) throws RemoteException {

    final Object[] resultHolder = new Object[1];
    Runnable pingRunnable = new Runnable() {
        public void run() {
            try {
                servant.ping();//  w w w .  j  av  a  2  s  . com
                resultHolder[0] = PING_DONE;
            } catch (Exception e) {
                final boolean wasInterrupted = Thread.interrupted();
                if (wasInterrupted) {
                    resultHolder[0] = new PingInterrupted();
                } else {
                    resultHolder[0] = e;
                }
            }
        }
    };

    Thread pingThread = InterruptibleRMIThreadFactory.getInstance().newThread(pingRunnable);
    pingThread.start();

    long t1 = System.currentTimeMillis();
    while (resultHolder[0] == null) {
        if ((System.currentTimeMillis() - t1) > pingTimeOut) {
            pingThread.interrupt();
            resultHolder[0] = new PingTimeout();
            break;
        }
        try {
            Thread.sleep(10);
        } catch (Exception e) {
        }
    }

    if (resultHolder[0] instanceof Throwable) {
        throw (RemoteException) resultHolder[0];
    }

}

From source file:org.kchine.rpf.PoolUtils.java

public static void reset(final ManagedServant servant, long resetTimeOut) throws RemoteException {
    final Object[] resultHolder = new Object[1];
    Runnable resetRunnable = new Runnable() {
        public void run() {
            try {
                servant.reset();/*  w  ww . j  a v  a2s. c  o  m*/
                resultHolder[0] = RESET_DONE;
            } catch (Exception e) {
                final boolean wasInterrupted = Thread.interrupted();
                if (wasInterrupted) {
                    resultHolder[0] = new ResetInterrupted();
                } else {
                    resultHolder[0] = e;
                }
            }
        }
    };

    Thread resetThread = InterruptibleRMIThreadFactory.getInstance().newThread(resetRunnable);
    resetThread.start();

    long t1 = System.currentTimeMillis();
    while (resultHolder[0] == null) {
        if ((System.currentTimeMillis() - t1) > resetTimeOut) {
            resetThread.interrupt();
            resultHolder[0] = new ResetTimeout();
            break;
        }
        try {
            Thread.sleep(10);
        } catch (Exception e) {
        }
    }

    if (resultHolder[0] instanceof Throwable) {
        throw (RemoteException) resultHolder[0];
    }
}

From source file:com.splout.db.dnode.TestFetcher.java

@Test
public void testHdfsFetchingInterrupted() throws IOException, URISyntaxException, InterruptedException {
    Configuration conf = new Configuration();
    final FileSystem fS = FileSystem.getLocal(conf);

    SploutConfiguration testConfig = SploutConfiguration.getTestConfig();
    testConfig.setProperty(FetcherProperties.TEMP_DIR, "tmp-dir-" + TestFetcher.class.getName());
    final Fetcher fetcher = new Fetcher(testConfig);

    final Path path = new Path("tmp-" + TestFetcher.class.getName());
    OutputStream oS = fS.create(path);
    oS.write("This is what happens when you don't know what to write".getBytes());
    oS.close();//from w ww .  j  av  a2 s .c o  m

    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                try {
                    File f = fetcher
                            .fetch(new Path(fS.getWorkingDirectory(), path.getName()).toUri().toString());
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                fail("An InterruptedException was expected.");
            } catch (InterruptedException e) {
                // Everything good.
            }
        }
    };
    // We interrupt the thread before starting so we are sure that the interruption check
    // will be seen even if the file to copy is very small.
    t.interrupt();
    t.start();
}

From source file:com.dirkgassen.wator.ui.activity.MainActivity.java

/** The activity is pausing. Stop the simulator thread and the world updater thread. */
@Override/*from   w  w  w  . j a v a2  s  .  c  o  m*/
protected void onPause() {
    super.onPause();
    synchronized (this) {
        Thread t = worldUpdateNotifierThread;
        worldUpdateNotifierThread = null;
        if (t != null) {
            t.interrupt();
        }
        simulatorRunnable.stopTicking();
    }
}