문제

할 수 있는 방법 프로그래밍 방식으로 을 감지하는 교착 상태에서 발생하는 Java 프로그램입니까?

올바른 솔루션이 없습니다

다른 팁

당신은 이것을 프로그래밍 방식으로 사용할 수 있습니다 ThreadMXBean JDK와 함께 배송합니다.

ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long[] threadIds = bean.findDeadlockedThreads(); // Returns null if no threads are deadlocked.

if (threadIds != null) {
    ThreadInfo[] infos = bean.getThreadInfo(threadIds);

    for (ThreadInfo info : infos) {
        StackTraceElement[] stack = info.getStackTrace();
        // Log or store stack trace information.
    }
}

분명히 당신은이 교착 상태 검사를 수행하는 스레드를 분리하려고 시도해야합니다. 그렇지 않으면 스레드 교착 상태가 있으면 수표를 실행할 수 없습니다!

우연히 이것은 jconsole이 커버 아래에서 사용하는 것입니다.

조사를위한 유용한 힌트 중 하나 :

응용 프로그램을 잡을 수 있고 교착 상태가 발생했다고 의심하면 java.exe 콘솔 창 (또는 Solaris/Linux의 "Ctrl- ")에서 "Ctrl-Break"를 누르고 누르십시오. JVM은 모든 스레드의 현재 상태 및 스택 추적을 덤프하고 데드 잠금 장치를 찾고 정확하게 설명합니다.

다음과 같이 보일 것입니다.

Full thread dump Java HotSpot(TM) Client VM (1.5.0_09-b03 mixed mode):

"[Test Timer] Request Queue" prio=6 tid=0x13d708d0 nid=0x1ec in Object.
    wait() [0x1b00f000..0x1b00fb68]
    at java.lang.Object.wait(Native Method)
    at java.lang.Object.wait(Unknown Source)
    at library.util.AsyncQueue.run(AsyncQueue.java:138)
        - locked <0x02e70000> (a test.server.scheduler.SchedulerRequestQueue)

    ...

Found one Java-level deadlock:
=============================
"Corba service":
  waiting to lock monitor 0x13c06684 (object 0x04697d90, a java.lang.Object),
  which is held by "[Server Connection] Heartbeat Timer"
"[Server Connection] Heartbeat Timer":
  waiting to lock monitor 0x13c065c4 (object 0x0467e728, a test.proxy.ServerProxy), which is held by "Corba service"

Java stack information for the threads listed above:
===================================================
"Corba service":
    at test.proxy.ServerProxy.stopHBWatchDog(ServerProxy:695)
    - waiting to lock <0x04697d90> (a java.lang.Object)
    ...

ThreadMxBean 클래스를 사용하여 프로그래밍 방식으로 교착 상태를 감지 할 수 있습니다.

    ThreadMXBean bean = ManagementFactory.getThreadMXBean();

    long ids[] = bean.findMonitorDeadlockedThreads();

    if(ids != null)
    {
        ThreadInfo threadInfo[] = bean.getThreadInfo(ids);

        for (ThreadInfo threadInfo1 : threadInfo)
        {
            System.out.println(threadInfo1.getThreadId());    //Prints the ID of deadlocked thread

            System.out.println(threadInfo1.getThreadName());  //Prints the name of deadlocked thread

            System.out.println(threadInfo1.getLockName());    //Prints the string representation of an object for which thread has entered into deadlock.

            System.out.println(threadInfo1.getLockOwnerId());  //Prints the ID of thread which currently owns the object lock

            System.out.println(threadInfo1.getLockOwnerName());  //Prints name of the thread which currently owns the object lock.
        }
    }
    else
    {
        System.out.println("No Deadlocked Threads");
    }

딸깍 하는 소리 여기 교착 상태를 감지하는 방법에 대한 자세한 정보.

Jarmus 교착 상태 감지 및 회피를위한 라이브러리입니다. 지원이 포함되어 있습니다.Thread.join, CyclicBarrier, CountDownLatch, Phaser, 그리고ReentrantLock.

Jarmus를 사용하려면 코드를 도구해야합니다. 계측 클래스 중 하나를 통해 또는 Jarmus Instrumentar와 자동으로 jarmusc.

java -jar jarmusc.jar yourprogram.jar checkedprogram.jar

입력 yourprogram.jar 확인하려는 프로그램입니다. 출력은 교착 상태를 자동으로 찾을 수있는 수표와 동일한 프로그램입니다.

장벽에는 도움이 필요합니다

수업으로 교착 상태를 확인합니다 CyclicBarrier, CountDownLatch, Phaser 예를 들어, JConsole은 이러한 유형의 교착 상태를 감지 할 수 없습니다. Jarmus는 귀하의 도움이 필요합니다. 동기화에 영향을 미치는 스레드를 지정해야합니다. 등기 스레드.

가능한 빨리 스레드는 등록 된대로 자체 표시해야합니다. 등록 된 스레드를 표시하기에 좋은 장소는 시작 방법입니다. Runnable.run. JArmus.register(latch);

예시

교착 상태가 Jarmus에 의해 올바르게 식별되는 다음 프로그램 :

final CountDownLatch latch = new CountDownLatch(2);
final CyclicBarrier barrier = new CyclicBarrier(2);
final Queue<Exception> exceptions = new ArrayDeque<>();
Thread t1 = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            JArmus.register(barrier); // do not forget to register!
            JArmus.register(latch); // do not forget to register!
            latch.countDown();
            latch.await();
            barrier.await();
        } catch (Exception e) {
            exceptions.add(e);
        }
    }
});
Thread t2 = new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            JArmus.register(barrier); // do not forget to register!
            JArmus.register(latch); // do not forget to register!
            barrier.await();
            latch.countDown();
            latch.await();
        } catch (Exception e) {
            exceptions.add(e);
        }
    }
});
t1.start();
t2.start();

고려하고 싶을 수도 있습니다 IBM의 mtrat. 결국 예방은 치료보다 낫습니다. 그만큼 멀티 코어 소프트웨어 개발 키트 교착 상태 감지 도구도 함께 제공됩니다.

프로그래밍 방식 감지가 필요하지 않으면 jconsole; 스레드 탭에는 "교착 상태 감지"버튼이 있습니다. JDK6에서 이것은 고유 한 모니터와 모두에 대한 잠금을 감지합니다. j.u.c Lock에스

the를 통해 jconsole을 실행하십시오 $JAVA_HOM/bin/jconsole 명령

거기에 여기에 코드: http://www.java2s.com/Code/Java/Development-Class/PerformingdeadlockdetectionprogrammaticallywithintheapplicationusingthejavalangmanagementAPI.htm

마법에서 발생 ThreadMonitor.findDeadlock():

  public boolean findDeadlock() {
    long[] tids;
    if (findDeadlocksMethodName.equals("findDeadlockedThreads")
        && tmbean.isSynchronizerUsageSupported()) {
      tids = tmbean.findDeadlockedThreads();
      if (tids == null) {
        return false;
      }

      System.out.println("Deadlock found :-");
      ThreadInfo[] infos = tmbean.getThreadInfo(tids, true, true);
      for (ThreadInfo ti : infos) {
        printThreadInfo(ti);
        printLockInfo(ti.getLockedSynchronizers());
        System.out.println();
      }
    } else {
      tids = tmbean.findMonitorDeadlockedThreads();
      if (tids == null) {
        return false;
      }
      ThreadInfo[] infos = tmbean.getThreadInfo(tids, Integer.MAX_VALUE);
      for (ThreadInfo ti : infos) {
        // print thread information
        printThreadInfo(ti);
      }
    }

    return true;
  }

이 API 의 ThreadMXBean 는 이름이 다른 자바에서는 5,6(따라서 바깥 if()).

코드를 들어도 중단하려면 잠금할 수 있도록 끊습니다.

템포 푸트 또한 프로그래밍 방식 스레드 덤핑 클래스와 함께 구현합니다. 위에서 언급 한 MBEAN 메커니즘을 사용하여 구현되었으며 Box 외부 슈퍼 듀퍼 솔루션을 드롭게합니다.

런타임에 수행하기를 원하는 경우 사용할 수 있습니다. 지키는 개 그에 대한.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top