/** taken from sun.misc.VM * * Returns Thread.State for the given threadStatus */ private static Thread.State toThreadState(int threadStatus) { if ((threadStatus & JVMTI_THREAD_STATE_RUNNABLE) != 0) { return State.RUNNABLE; } else if ((threadStatus & JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER) != 0) { return State.BLOCKED; } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_INDEFINITELY) != 0) { return State.WAITING; } else if ((threadStatus & JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT) != 0) { return State.TIMED_WAITING; } else if ((threadStatus & JVMTI_THREAD_STATE_TERMINATED) != 0) { return State.TERMINATED; } else if ((threadStatus & JVMTI_THREAD_STATE_ALIVE) == 0) { return State.NEW; } else { return State.RUNNABLE; } }
SampledThreadInfo(String tn, long tid, Thread.State ts, StackTraceElement[] st, InstrumentationFilter filter) { threadName = tn; threadId = tid; state = ts; stackTrace = st; if (state == Thread.State.RUNNABLE && containsKnownBlockingMethod(st)) { // known blocking method -> change state to waiting state = Thread.State.WAITING; } if (filter != null) { int i; for (i=0; i<st.length; i++) { StackTraceElement frame = st[i]; if (filter.passes(frame.getClassName().replace('.','/'))) { // NOI18N if (i>1) { stackTrace = new StackTraceElement[st.length-i+1]; System.arraycopy(st,i-1,stackTrace,0,stackTrace.length); } break; } } if (i==st.length) { stackTrace = NO_STACK_TRACE; } } }
@Test public void testAddStacktraceWaitingPlus() { System.out.println("add stacktrace : waiting/plus"); setState(stack0[0],Thread.State.WAITING); addStacktrace(stack0, 0); long timestamp = 500000; setState(stackPlus[2],Thread.State.RUNNABLE); addStacktrace(stackPlus, timestamp); assertEquals(Math.max(stack0.length, stackPlus.length), instance.threadIds.size()); assertEquals(Math.max(elements0.length, elementsPlus.length), instance.methodInfos.size()-1); assertEquals(timestamp, instance.currentDumpTimeStamp); }
@Test public void testAddStackTraceWaitRun() { System.out.println("add stacktrace : wait->run"); addStacktrace(stack0, 0); setState(stack0[0], Thread.State.WAITING); addStacktrace(stack0, 500000); assertEquals(500000, instance.currentDumpTimeStamp); assertEquals(Thread.State.WAITING, instance.lastStackTrace.get().get(thread0.getId()).getThreadState()); setState(stack0[0], Thread.State.RUNNABLE); addStacktrace(stack0, 1000000); assertEquals(1000000, instance.currentDumpTimeStamp); assertEquals(Thread.State.RUNNABLE, instance.lastStackTrace.get().get(thread0.getId()).getThreadState()); }
@Test public void testAddStackTraceWaitWait() { System.out.println("add stacktrace : wait->wait"); addStacktrace(stack0, 0); setState(stack0[0], Thread.State.WAITING); addStacktrace(stack0, 500000); assertEquals(500000, instance.currentDumpTimeStamp); assertEquals(Thread.State.WAITING, instance.lastStackTrace.get().get(thread0.getId()).getThreadState()); addStacktrace(stack0, 1000000); assertEquals(1000000, instance.currentDumpTimeStamp); assertEquals(Thread.State.WAITING, instance.lastStackTrace.get().get(thread0.getId()).getThreadState()); }
@Test public void testAddStackTraceWaitBlocked() { System.out.println("add stacktrace : wait->blocked"); addStacktrace(stack0, 0); setState(stack0[0], Thread.State.WAITING); addStacktrace(stack0, 500000); assertEquals(500000, instance.currentDumpTimeStamp); assertEquals(Thread.State.WAITING, instance.lastStackTrace.get().get(thread0.getId()).getThreadState()); setState(stack0[0], Thread.State.BLOCKED); addStacktrace(stack0, 1000000); assertEquals(1000000, instance.currentDumpTimeStamp); assertEquals(Thread.State.BLOCKED, instance.lastStackTrace.get().get(thread0.getId()).getThreadState()); }
@Test public void testGC() throws Exception { CountDownLatch done = new CountDownLatch(1); Scheduler scheduler = RxSchedulers.fixedSize(1); FinalizeSupport.finalize(scheduler, done::countDown); Wrapper<Thread> worker = Wrapper.empty(); Observable.just(1) .subscribeOn(scheduler) .doOnNext(i -> worker.set(Thread.currentThread())) .blockingSubscribe(); scheduler = null; System.gc(); assertTrue(done.await(100, TimeUnit.MILLISECONDS)); assertNotNull(worker.get()); for (int i = 0; i < 20; i++) { System.gc(); Thread.sleep(5); if (worker.get().getState() == State.TERMINATED) { return; } } assertEquals(State.TERMINATED, worker.get().getState()); }
/** * Returns Cassandra driver session to sessions pool. * * @param cassandraSes Session wrapper. * @param driverSes Driver session. */ public static void put(CassandraSessionImpl cassandraSes, Session driverSes) { if (cassandraSes == null || driverSes == null) { return; } SessionWrapper old; synchronized (sessions) { old = sessions.put(cassandraSes, new SessionWrapper(driverSes)); if (monitorSingleton == null || State.TERMINATED.equals(monitorSingleton.getState())) { monitorSingleton = new SessionMonitor(); monitorSingleton.setDaemon(true); monitorSingleton.setName("Cassandra-sessions-pool"); monitorSingleton.start(); } } if (old != null) { old.release(); } }
/** * 结束作业,包含子作业和转换 <br/> * @author jingma * @param job */ @SuppressWarnings("deprecation") public static void jobKillAll(Job job){ job.stopAll(); JobMeta jobMeta = job.getJobMeta(); for(JobEntryCopy jec:jobMeta.getJobCopies()){ if(jec.isTransformation()){ JobEntryTrans jet = (JobEntryTrans)jec.getEntry(); if(jet.getTrans()!=null){ jet.getTrans().killAll(); } }else if(jec.isJob()){ JobEntryJob jej = (JobEntryJob)jec.getEntry(); if(jej.getJob()!=null){ jobKillAll(jej.getJob()); } } } //采用线程中断结束卡住的线程 if(job.getState().equals(State.BLOCKED)||job.getState().equals(State.TIMED_WAITING)){ job.stop(); }else{ job.interrupt(); } }
/** * This is to avoid race condition in the test case. NodeStatusUpdater * heartbeat thread after sending the heartbeat needs some time to process the * response and then go wait state. But in the test case once the main test * thread returns back after resourceTracker.waitTillHeartbeat() we proceed * with next sendOutofBandHeartBeat before heartbeat thread is blocked on * wait. * @throws InterruptedException * @throws IOException */ private void sendOutofBandHeartBeat() throws InterruptedException, IOException { int i = 0; do { State statusUpdaterThreadState = ((NodeStatusUpdaterImpl) nm.getNodeStatusUpdater()) .getStatusUpdaterThreadState(); if (statusUpdaterThreadState.equals(Thread.State.TIMED_WAITING) || statusUpdaterThreadState.equals(Thread.State.WAITING)) { nm.getNodeStatusUpdater().sendOutofBandHeartBeat(); break; } if (++i <= 10) { Thread.sleep(50); } else { throw new IOException( "Waited for 500 ms but NodeStatusUpdaterThread not in waiting state"); } } while (true); }
public boolean isReadable() { if (_thread == null) { return true; } else { synchronized (_thread) { if (_thread.getState() == State.WAITING) { return true; } else if (_thread.getState() == State.TIMED_WAITING) { // Make sure that it stays readable _tcx.waitUntilNotified(true); return true; } return false; } } }
private void start() { if( _thread == null || _thread.getState() == State.TERMINATED ) { _isTerminated = false; _thread = new Thread( this, _algorithm.name() + "." + _tcx.getTriangulationMode() ); _thread.start(); sendEvent( TriangulationProcessEvent.Started ); } else { // Triangulation already running. Terminate it so we can start a new shutdown(); _restart = true; } }
public void resume() { if( _thread != null ) { // Only force a resume when process is waiting for a notification if( _thread.getState() == State.WAITING ) { synchronized( _tcx ) { _tcx.notify(); } } else if( _thread.getState() == State.TIMED_WAITING ) { _tcx.waitUntilNotified( false ); } } }
public boolean isReadable() { if( _thread == null ) { return true; } else { synchronized( _thread ) { if( _thread.getState() == State.WAITING ) { return true; } else if( _thread.getState() == State.TIMED_WAITING ) { // Make sure that it stays readable _tcx.waitUntilNotified( true ); return true; } return false; } } }
private void calculateLabel() { StringBuilder str = new StringBuilder(); str.append("["); for(Entry<Thread.State, Integer> entry:states.entrySet()) { str.append(entry.getKey()); str.append(" "); try { BigDecimal percentage = new BigDecimal((100.0*entry.getValue())/sampleCount); percentage = percentage.setScale(0,RoundingMode.HALF_EVEN); str.append(percentage); } catch (Exception e) { logger.error("Error while calculation label "+str.toString(),e); } str.append("% "); } str.append("]"); label = name + str.toString(); }
@Test public void unaffectedValues() throws Exception { final List<Object> unnafected = asList( BigDecimal.valueOf(2348.123), false, (byte) 1234, (double) 132948, State.RUNNABLE, (float) 352.123, now(), 8482539, new ArrayList<>(), (long) 1234512, (short) 3174, "strigsy495"); for (final Object value : unnafected) assertEquals(value, new Sanitizer(value).sanitize()); }
@Test public void asList() throws Exception { final Instant now = now(); final RestModel restModel = RestModel.newRestModel(); final List<Triplet<Class<?>, Object, Object>> fixtures = new ArrayList<>(); fixtures.add(new Triplet<>(Boolean.class, Arrays.asList(true), Arrays.asList(true))); fixtures.add(new Triplet<>(Byte.class, Arrays.asList((byte) 1), Arrays.asList((byte) 1))); fixtures.add(new Triplet<>(Short.class, Arrays.asList((short) 1), Arrays.asList((short) 1))); fixtures.add(new Triplet<>(Integer.class, Arrays.asList(1), Arrays.asList(1))); fixtures.add(new Triplet<>(Long.class, Arrays.asList(1l), Arrays.asList(1l))); fixtures.add(new Triplet<>(String.class, Arrays.asList("name"), Arrays.asList("name"))); fixtures.add(new Triplet<>(State.class, Arrays.asList("BLOCKED"), Arrays.asList(BLOCKED))); fixtures.add(new Triplet<>(Instant.class, Arrays.asList(now), Arrays.asList(now))); fixtures.add(new Triplet<>(RestModel.class, Arrays.asList(restModel), Arrays.asList(restModel))); for (int i = 0; i < fixtures.size(); i++) { final Triplet<Class<?>, Object, Object> fixture = fixtures.get(i); final Class<?> type = fixture.getValue0(); final Object input = fixture.getValue1(); final Object expected = fixture.getValue2(); final List<?> output = new RestValue(input).asListOf(type); assertEquals(expected, output); } }
public String connectionRequest() { if (crw == null || crw.getState() == State.TERMINATED) { try { System.out.println("Connection request START"); HostsLocal h = Ejb.lookupHostsBean().findByHwidAndSn(hwid, sn); // crw = new ConnectionRequestWorker(url, conreqUser, conreqPass); crw = new ConnectionRequestWorker(h); setLastcrres("In progress"); crw.start(); } catch (FinderException ex) { System.out.println("FinderException: " + ex.getLocalizedMessage()); setLastcrres(ex.getLocalizedMessage()); Logger.getLogger(HostsBean.class.getName()).log(Level.SEVERE, null, ex); } } else { System.out.println("Connection request no......"); } return null; }
private static synchronized void trackAllocatedHashinatorBytes(long bytes) { final long allocated = m_allocatedHashinatorBytes.addAndGet(bytes); if (allocated > HASHINATOR_GC_THRESHHOLD) { hostLogger.warn(allocated + " bytes of hashinator data has been allocated"); if (m_emergencyGCThread == null || m_emergencyGCThread.getState() == State.TERMINATED) { m_emergencyGCThread = new Thread(new Runnable() { @Override public void run() { hostLogger.warn("Invoking System.gc() to recoup hashinator bytes"); System.gc(); try { Thread.sleep(2000); } catch (InterruptedException e) {} hostLogger.info(m_allocatedHashinatorBytes.get() + " bytes of hashinator allocated after GC"); } }, "Hashinator GC thread"); m_emergencyGCThread.start(); } } }
@Test public void testWaitingInfinitely() throws Exception { final RunnableConsumerStageTestConfig configuration = new RunnableConsumerStageTestConfig(0, 1, 2, 3, 5); assertThat(configuration.getCollectorSink().getCurrentState(), is(StageState.CREATED)); assertThat(configuration.getConsumerThread(), is(nullValue())); // starts the threads, but does not send the start signal new Execution<RunnableConsumerStageTestConfig>(configuration); assertThat(configuration.getCollectorSink().getCurrentState(), is(StageState.VALIDATED)); Thread.sleep(200); assertThat(configuration.getCollectorSink().getCurrentState(), is(StageState.VALIDATED)); // still validated assertThat(configuration.getConsumerThread().getState(), is(State.WAITING)); assertThat(configuration.getCollectedElements().size(), is(0)); }
/** * Returns Cassandra driver session to sessions pool. * * @param cassandraSes Session wrapper. * @param driverSes Driver session. */ public static void put(CassandraSessionImpl cassandraSes, Session driverSes, long expirationTimeout) { if (cassandraSes == null || driverSes == null) return; SessionWrapper old; synchronized (sessions) { old = sessions.put(cassandraSes, new SessionWrapper(driverSes, expirationTimeout)); if (monitorSingleton == null || State.TERMINATED.equals(monitorSingleton.getState())) { monitorSingleton = new SessionMonitor(); monitorSingleton.setDaemon(true); monitorSingleton.setName("Cassandra-sessions-pool"); monitorSingleton.start(); } } if (old != null) old.release(); }
@Test @BMRule(name = "Greatest name in the world", targetClass="HintsBufferPool", targetMethod="switchCurrentBuffer", targetLocation="AT INVOKE java.util.concurrent.BlockingQueue.take", action="org.apache.cassandra.hints.HintsBufferPoolTest.blockedOnBackpressure = true;") public void testBackpressure() throws Exception { Queue<HintsBuffer> returnedBuffers = new ConcurrentLinkedQueue<>(); HintsBufferPool pool = new HintsBufferPool(256, (buffer, p) -> returnedBuffers.offer(buffer)); Thread blocked = new Thread(() -> { for (int ii = 0; ii < 512; ii++) pool.write(ImmutableList.of(UUID.randomUUID()), HintsBufferTest.createHint(ii, ii)); }); blocked.start(); Util.spinAssertEquals(State.WAITING, () -> blocked.getState(), 1); while (blocked.isAlive()) if (!returnedBuffers.isEmpty()) pool.offer(returnedBuffers.poll().recycle()); assertTrue(blockedOnBackpressure); }
protected final void checkTaskIsBlocked(LoggingRunnable runningTask) { /* * ... or is blocked soon. Common pattern is to have two barriers in the Runnable, and await once in the main * thread. Once that first barrier has been passed the Runnable is definitely running, and it'll be blocking * on the barrier in a moment. */ Thread thread = runningTask.getRunningThread(); assertThat("Task was expected to be in blocked state, but it hasn't started yet. Task: " + runningTask, thread != null); State state = thread.getState(); int tries = 0; while (tries++ < 5 && !BLOCKING_STATES.contains(state)) { // give it just a little pause to see if we need to wait trySleep(10); state = thread.getState(); } assertThat("Expected task in a blocked state (one of " + BLOCKING_STATES + ") but it was " + state, BLOCKING_STATES.contains(state)); }
/** * Call to start or reset a count down to execution of the current state's * command. */ private void startCountDownToExecution() { try { countDownSemaphore.acquire(); if (countDownThread == null || countDownThread.getState() == State.TERMINATED) { countDownThread = new Thread(countDownRunnable); countDownThread.start(); } else { timeToExecution = BTN_PRESS_INTERVAL; } } catch (Exception e) { Log.e(TAG, e.toString()); } finally { countDownSemaphore.release(); } }
public void start(VideoGridFragment videoGridFragment) { if (mLibVlc == null) { try { mLibVlc = VLCInstance.getLibVlcInstance(); } catch (LibVlcException e) { Log.e(TAG, "Can't obtain libvlc instance"); e.printStackTrace(); return; } } isStopping = false; if (mThread == null || mThread.getState() == State.TERMINATED) { mVideoGridFragment = videoGridFragment; mThread = new Thread(this); mThread.start(); } }
public static List<Thread> currentThreads() { List<Thread> threads = Lists.newArrayList(); for (Thread thread : Thread.getAllStackTraces().keySet()) { // DestroyJavaVM is a JVM thread that appears sporadically, easier to just filter it out // // AWT-AppKit is a JVM thread on OS X that appears during webdriver tests // // "process reaper" are JVM threads on linux that monitors subprocesses, these use a // thread pool in jdk7 and so the threads stay around in the pool even after the // subprocess ends, they show up here when mixing local container and javaagent // container tests since javaagent container tests create subprocesses and then local // container tests check for rogue threads and find these if (thread.getState() != State.TERMINATED && !thread.getName().equals("DestroyJavaVM") && !thread.getName().equals("AWT-AppKit") && !thread.getName().equals("process reaper")) { threads.add(thread); } } return threads; }