本文整理匯總了Java中java.lang.Thread.State.BLOCKED屬性的典型用法代碼示例。如果您正苦於以下問題:Java State.BLOCKED屬性的具體用法?Java State.BLOCKED怎麽用?Java State.BLOCKED使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類java.lang.Thread.State
的用法示例。
在下文中一共展示了State.BLOCKED屬性的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: toThreadState
/** 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;
}
}
示例2: setNewDataWorker
private void setNewDataWorker() {
if (this.dataThread != null) {
this.dataWorker.induceStop();
if (this.dataThread != Thread.currentThread()) {
State state = this.dataThread.getState();
if (state == State.BLOCKED || state == State.WAITING)
this.dataThread.interrupt();
}
}
this.dataTasks = new LinkedBlockingQueue<DataTask>();
this.dataWorker = new DataWorker(this, this.currentSession, this.dataTasks);
this.dataThread = new Thread(dataWorker);
this.dataThread.setName("Data Worker for " + this.currentSession);
this.dataThread.start();
}
示例3: asEnum
@Test
public void asEnum() throws Exception {
final State expected = State.BLOCKED;
assertEquals(expected, new RestValue("BLOCKED").asEnum(State.class));
}
示例4: checkForDeadlock
private static void checkForDeadlock(EditingDomain domain) {
try {
// I am the display thread
if (domain instanceof InternalTransactionalEditingDomain) {
InternalTransactionalEditingDomain internalDomain = (InternalTransactionalEditingDomain) domain;
InternalTransaction activeTransaction = internalDomain.getActiveTransaction();
if (activeTransaction != null) {
// There is already an active transaction
Thread owner = activeTransaction.getOwner();
Thread currentThread = Thread.currentThread();
if (owner != currentThread) {
// I'm going to block/run display runnable
if (owner.getState() == State.BLOCKED) {
checkForBasicDeadlock();
// The transaction owner is blocked too
long ownerId = owner.getId();
ThreadInfo threadInfo = null;
long nextId = ownerId;
while (nextId != -1) {
threadInfo = THREAD_MX_BEAN.getThreadInfo(nextId, 2);
if (threadInfo == null) {
break; // the thread being blocked on has terminated
}
nextId = threadInfo.getLockOwnerId();
if (nextId == ownerId) {
String message = "the transaction is held by a deadlock 2";
Logger.getLogger(TransactionUtils.class).error(message);
}
}
checkForThreadJobJoinRun(threadInfo);
}
}
}
}
} catch (RuntimeException e) {
Logger.getLogger(TransactionUtils.class).error("exception in TransactionUtils", e);
}
}
示例5: shutdownThreads
public static void shutdownThreads() {
if (persistenceThread != null) {
worker.induceStop();
State state = persistenceThread.getState();
int tasks = worker.getNumTasks();
if (tasks == 0 && (state == State.BLOCKED || state == State.WAITING))
persistenceThread.interrupt();
persistenceThread = null;
}
}
示例6: testGuid
/**
* Tests the improvement added by using a SecureRandom pool when generating GUID's
*/
public void testGuid()
{
// warm-up (to pre-init the secureRandomArray)
GUID.generate();
List<Thread> threads = new ArrayList<>();
int n = 30;
for (int i = 0; i < n; i++)
{
Thread thread = new Thread(new GuidRunner());
threads.add(thread);
thread.start();
}
Set<String> blocked = new HashSet<String>();
Set<String> terminated = new HashSet<String>();
int maxItemsBlocked = 0;
while (terminated.size() != n)
{
for (Thread current : threads)
{
State state = current.getState();
String name = current.getName();
if (state == State.BLOCKED)
{
if (!blocked.contains(name))
{
blocked.add(name);
maxItemsBlocked = blocked.size() > maxItemsBlocked ? blocked.size() : maxItemsBlocked;
}
}
else // not BLOCKED, eg. RUNNABLE, TERMINATED, ...
{
blocked.remove(name);
if (state == State.TERMINATED && !terminated.contains(name))
{
terminated.add(name);
}
}
}
}
//worst case scenario : max number of threads blocked at a moment = number of threads - 2 ( usually ~5 for 30 threads)
//the implementation without RandomSecure pool reaches constantly (number of threads - 1) max blocked threads
Assert.assertTrue("Exceeded number of blocked threads : " + maxItemsBlocked, maxItemsBlocked < n-2);
}
示例7: threadDump
/**
* Dumps all of the threads' current information to an output stream.
*
* @param out an output stream
*/
public void threadDump(OutputStream out) {
final ThreadInfo[] threads = this.threads.dumpAllThreads(true, true);
final PrintWriter writer = new PrintWriter(out, true);
for (int ti = threads.length - 1; ti >= 0; ti--) {
final ThreadInfo t = threads[ti];
writer.printf("%s id=%d state=%s",
t.getThreadName(),
t.getThreadId(),
t.getThreadState());
final LockInfo lock = t.getLockInfo();
if (lock != null && t.getThreadState() != State.BLOCKED) {
writer.printf("\n - waiting on <0x%08x> (a %s)",
lock.getIdentityHashCode(),
lock.getClassName());
writer.printf("\n - locked <0x%08x> (a %s)",
lock.getIdentityHashCode(),
lock.getClassName());
} else if (lock != null && t.getThreadState() == State.BLOCKED) {
writer.printf("\n - waiting to lock <0x%08x> (a %s)",
lock.getIdentityHashCode(),
lock.getClassName());
}
if (t.isSuspended()) {
writer.print(" (suspended)");
}
if (t.isInNative()) {
writer.print(" (running in native)");
}
writer.println();
if (t.getLockOwnerName() != null) {
writer.printf(" owned by %s id=%d\n", t.getLockOwnerName(), t.getLockOwnerId());
}
final StackTraceElement[] elements = t.getStackTrace();
final MonitorInfo[] monitors = t.getLockedMonitors();
for (int i = 0; i < elements.length; i++) {
final StackTraceElement element = elements[i];
writer.printf(" at %s\n", element);
for (int j = 1; j < monitors.length; j++) {
final MonitorInfo monitor = monitors[j];
if (monitor.getLockedStackDepth() == i) {
writer.printf(" - locked %s\n", monitor);
}
}
}
writer.println();
final LockInfo[] locks = t.getLockedSynchronizers();
if (locks.length > 0) {
writer.printf(" Locked synchronizers: count = %d\n", locks.length);
for (LockInfo l : locks) {
writer.printf(" - %s\n", l);
}
writer.println();
}
}
writer.println();
writer.flush();
}
示例8: run
@Override
public void run() {
try {
while (runLogLoop) {
try {
final EventLogManager eventLogManager = EventLogManager.getInstance();
// Code inspiré de http://knight76.blogspot.fr/2009/05/how-to-get-java-cpu-usage-jvm-instance.html et http://www.docjar.com/html/api/sun/tools/jconsole/SummaryTab$Result.java.html
final SystemEventLog systemEventLog = eventLogManager.addEventLog(SystemEventLog.class);
final OperatingSystemMXBean osMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
final long processCpuTime = osMXBean.getProcessCpuTime();
final RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
final long uptime = runtimeMXBean.getUptime();
final int availableProcessors = osMXBean.getAvailableProcessors();
final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
systemEventLog.setHeapMemoryUsed(memoryMXBean.getHeapMemoryUsage().getUsed());
systemEventLog.setNonHeapMemoryUsed(memoryMXBean.getNonHeapMemoryUsage().getUsed());
final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
systemEventLog.setThreadCount(threadMXBean.getThreadCount());
systemEventLog.setPeakThreadCount(threadMXBean.getPeakThreadCount());
// Compute the cpuUsage
if (prevUptime > 0L && uptime > prevUptime) {
// elapsedCpu is in ns and elapsedTime is in ms.
final long elapsedCpu = processCpuTime - prevProcessCpuTime;
final long elapsedTime = uptime - prevUptime;
// cpuUsage could go higher than 100% because elapsedTime
// and elapsedCpu are not fetched simultaneously. Limit to
// 99% to avoid Plotter showing a scale from 0% to 200%.
systemEventLog.setCpuUsage(Math.min(100F, elapsedCpu / (elapsedTime * 10000F * availableProcessors))); // elapsedCpu / (elapsedTime * 1000F * 1000F * availableProcessors)) * 100 => pour l'avoir en %
}
systemEventLog.setUptime(uptime);
systemEventLog.setProcessCpuTime(processCpuTime);
systemEventLog.setAvailableProcessors(availableProcessors);
// We now log all threads in RUNNABLE or BLOCKED state
final ThreadInfo[] allThreads = threadMXBean.dumpAllThreads(false, false);
final List<SystemEventLog.Thread> loggedThreads = new LinkedList<SystemEventLog.Thread>();
for (final ThreadInfo threadInfo : allThreads) {
if (threadInfo != null) { // It seems that sometime (with JRockit) threadInfo is null
final State threadState = threadInfo.getThreadState();
if ((threadState == State.BLOCKED || threadState == State.RUNNABLE) && PatternUtils.matches(threadInfo.getThreadName(), threadNameIncludes, threadNameExcludes)) {
final long threadId = threadInfo.getThreadId();
loggedThreads.add(new SystemEventLog.Thread(threadInfo, threadMXBean.getThreadUserTime(threadId), threadMXBean.getThreadCpuTime(threadId)));
}
}
}
systemEventLog.setBlockedOrRunningThreads(loggedThreads.toArray(new SystemEventLog.Thread[loggedThreads.size()]));
eventLogManager.fire(systemEventLog);
SystemEventLogger.this.prevUptime = uptime;
SystemEventLogger.this.prevProcessCpuTime = processCpuTime;
Thread.sleep(cpuComputationDeltaMillis);
} catch (final InterruptedException e) {
throw new RuntimeException(e);
}
}
} finally {
stop();
}
}
示例9: run
@Override
public void run() {
LOGGER.info(String.format("Monitoring cache update using thread %s; considers .lock age? %s",
Thread.currentThread().getId(),
maximumAge != Long.MIN_VALUE));
Map<Thread, StackTraceElement[]> stacks = Thread.getAllStackTraces();
Thread target = null;
/*
* try to find the
*/
if (TimerTaskCacheScheduler.this.lastSchedulerThread != Long.MIN_VALUE) {
for (Thread t : stacks.keySet()) {
if (t.getId() == TimerTaskCacheScheduler.this.lastSchedulerThread) {
target = t;
break;
}
}
}
if (target != null) {
State state = target.getState();
LOGGER.info("lastSchedulerThread status: " + state);
LOGGER.info("lastSchedulerThread isalive: " + target.isAlive());
LOGGER.info("lastSchedulerThread isinterrupted: " + target.isInterrupted());
if (state != State.RUNNABLE && state != State.BLOCKED) {
LOGGER.info(String.format("Updater thread's stack: %s", createStackTrace(target.getStackTrace())));
}
}
else {
LOGGER.warn("Could not find lastSchedulerThread in current stack traces");
}
boolean isLocked = true;
isLocked = isCurrentyLocked();
if (isLocked) {
if (target != null && (target.getState() == Thread.State.TIMED_WAITING
|| target.getState() == Thread.State.WAITING)) {
LOGGER.warn("The cache update may have taken too long. trying to interrupt cache update.");
target.interrupt();
}
try {
if (this.maximumAge != Long.MIN_VALUE) {
LOGGER.info("Resolving age of cache.lock file");
File f = resolveCacheLockFile();
if (System.currentTimeMillis() - f.lastModified() > this.maximumAge) {
LOGGER.info("Trying to remove artifact cache.lock file due to its age");
freeCacheUpdateLock();
}
else {
LOGGER.info("cache.lock to young, an update might be in progress.");
}
}
else if (TimerTaskCacheScheduler.this.lastSchedulerThread != Long.MIN_VALUE) {
/*
* only free if this CacheScheduler instance (singleton in an SOE instance)
* has already started a cache update. otherwise lastSchedulerThread has
* not been set yet
*/
LOGGER.info("freeing cache.lock");
freeCacheUpdateLock();
}
}
catch (IOException e) {
LOGGER.warn(e.getMessage(), e);
}
}
else {
LOGGER.info("No stale cache.lock file found.");
}
}
示例10: getThreadDump
/**
* Dumps all of the threads' current information to an output stream.
*
* @param out an output stream
*/
public void getThreadDump(OutputStream out) {
final ThreadInfo[] threads = this.threads.dumpAllThreads(true, true);
final PrintWriter writer = new PrintWriter(out, true);
for (int ti = threads.length - 1; ti >= 0; ti--) {
final ThreadInfo t = threads[ti];
writer.printf("%s id=%d state=%s",
t.getThreadName(),
t.getThreadId(),
t.getThreadState());
final LockInfo lock = t.getLockInfo();
if ((lock != null) && (t.getThreadState() != State.BLOCKED)) {
writer.printf("\n - waiting on <0x%08x> (a %s)",
lock.getIdentityHashCode(),
lock.getClassName());
writer.printf("\n - locked <0x%08x> (a %s)",
lock.getIdentityHashCode(),
lock.getClassName());
} else if ((lock != null) && (t.getThreadState() == State.BLOCKED)) {
writer.printf("\n - waiting to lock <0x%08x> (a %s)",
lock.getIdentityHashCode(),
lock.getClassName());
}
if (t.isSuspended()) {
writer.print(" (suspended)");
}
if (t.isInNative()) {
writer.print(" (running in native)");
}
writer.println();
if (t.getLockOwnerName() != null) {
writer.printf(" owned by %s id=%d\n", t.getLockOwnerName(), t.getLockOwnerId());
}
final StackTraceElement[] elements = t.getStackTrace();
final MonitorInfo[] monitors = t.getLockedMonitors();
for (int i = 0; i < elements.length; i++) {
final StackTraceElement element = elements[i];
writer.printf(" at %s\n", element);
for (int j = 1; j < monitors.length; j++) {
final MonitorInfo monitor = monitors[j];
if (monitor.getLockedStackDepth() == i) {
writer.printf(" - locked %s\n", monitor);
}
}
}
writer.println();
final LockInfo[] locks = t.getLockedSynchronizers();
if (locks.length > 0) {
writer.printf(" Locked synchronizers: count = %d\n", locks.length);
for (LockInfo l : locks) {
writer.printf(" - %s\n", l);
}
writer.println();
}
}
writer.println();
writer.flush();
}