Java Multithreading: Deadlock

Source: Internet
Author: User

See an example of using Jstack to view a deadlock on the weekend. Last night summed up the Jstack (view thread), Jmap (view memory), and Jstat (performance analysis) commands. For everyone's reference
1. Jstack 1.1 Jstack can get information on Java stack and native stack running Java programs. It is easy to know how the current thread is running. As shown

Note: This and thread dump are the same result. But thread dump is using the kill-3 PID command, or the server is less use Kill for the wonderful1.2   named row format  
jstack [option] pid 
jstack [option] executable core 
jstack [option] [[EMAIL PROTECTED]]REMOTE-HOSTNAME-OR-IP 
The most commonly used is jstack  pid 

1.3   in thread dump, be aware of the following States  
Deadlock, deadlock (Focus)  
Wait for the resource, waiting on Condition (focus on)  
  Wait for the monitor, waiting on Monitor entry (focus)  
Blocked, blocked (focus on)  
  execution, runnable 
·   Pause, suspended 
  Object waits, object.wait () or timed_waiting 
  Stop, parked 
Here is a detailed example of this analysis, we refer to the original  
http://www.cnblogs.com/zhengyun_ustc/ archive/2013/01/06/dumpanalysis.html 

1.4   in thread dump, there are several threads defined as follows  

description of the thread name to which it belongs
Attach LISTENERJVM The Attach Listener thread is responsible for receiving external commands and executing the command and returning the result to the sender. Usually we use some commands to ask the JVM to give us some feedback, such as Java-version, Jmap, Jstack, and so on. If the thread is not initialized when the JVM is started, it will be started when the user first executes the JVM command.

Signal DISPATCHERJVM before we mentioned the first attach listener thread is responsible for receiving external JVM commands, and when the command is received successfully, it will be given to Signal Dispather Threads go through the process of distributing commands to various modules and returning processing results. The signal Dispather thread is also initialized when the external JVM command is received for the first time.

COMPILERTHREAD0JVM is used to invoke jiting to compile the loading class in real time. Typically, the JVM initiates multiple threads to handle this part of the work, and the number following the name of the thread is incremented, for example: CompilerThread1

The Concurrent mark-sweep GC THREADJVM Concurrent token clears the garbage collector (which is typically referred to as the CMS GC) thread, which is primarily intended for garbage collection in the old age. PS: To enable the garbage collector, you need to add the following JVM startup parameters:-XX:+USECONCMARKSWEEPGC

The thread that DESTROYJAVAVMJVM executes main () calls the JNI_DESTROYJAVAVM () method in Jni to invoke the DESTROYJAVAVM thread after main finishes executing. After the Jboss server is started, the JVM evokes the DESTROYJAVAVM thread, waits, waits for other threads (Java threads and native threads) to notify it to unload the JVM when it exits. When a thread exits, it will determine whether it is currently the last non-deamon thread in the entire JVM, and if so, notifies the DESTROYJAVAVM thread to unload the JVM.
Ps:
Expand:
1. If the thread exits with the judgment that it is not the last non-Deamon thread, call Thread->exit (false) and throw the Thread_end event in it, and the JVM does not exit.
2. If the thread exits with the last non-Deamon thread, call the Before_exit () method and throw two events: Event 1:thread_end thread End event, event 2:VM death event.
Then call the Thread->exit (True) method, then remove the thread from the active list, remove the thread, and so on, and then notify the waiting DESTROYJAVAVM thread to perform the unload JVM operation.
Containerbackgroundprocessor thread JBoss It is a daemon thread that initializes the JBoss server when it is started, and the main task is to check periodically if the session expires. Expired is cleared.
Reference: http://liudeh-009.iteye.com/blog/1584876
dispatcher-thread-3  thread log4j   LOG4J has the ability to print logs asynchronously, the Appender that require an asynchronous print log need to be registered with the Asyncappender object, monitored by asyncappender, and deciding when to trigger a log print operation. Asyncappender If the supervisor hears that appender in its jurisdiction has a print log operation, it generates a corresponding event for the Appender and saves the event in a Buffuer region.   DISPATCHER-THREAD-3 thread is responsible for determining if the event buffer is full, and if it is full, distribute all the event in the buffer to the Appender container. Those registered Appender receive their own event, then start processing their own log printing work. The dispatcher-thread-3 thread is a daemon thread.  
Finalizer thread JVM This thread is also created after the main thread, with a priority of 10, primarily used to call the Finalize () method of the object before garbage collection, and about the finalizer thread:
1) The Finalize () method is only started when a round of garbage collection is started, so not all of the object's Finalize () methods will be executed;
2) This thread is also a daemon thread, so the JVM exits if there are no other non-daemon threads in the virtual machine, whether or not the thread has completed the Finalize () method;
3) at garbage collection, the JVM wraps the object that is lost as a finalizer object (the implementation of the reference) and puts it in Referencequeue, which is handled by the finalizer thread, and finally the reference to the finalizer object is set to null. Collected by the garbage collector;
4) Why does the JVM have to use a single thread to execute the Finalize () method? If the JVM's garbage collection thread is doing it itself, it is likely that the GC thread will be stopped or not controlled due to a mistake in the Finalize () method, which is a disaster for GC threads;

Gang WORKER#0JVM A thread used by the JVM to do a generation of garbage collection (Monir GC). #号后面是线程编号, for example: Gang worker#1

GC DAEMONJVM GC Daemon threads are used by the JVM to provide remote distributed GC for RMI, and the GC Daemon thread will actively invoke the System.GC () method to perform full GC on the server. The intention is that when the RMI server returns an object to its client (the caller of the remote method), it tracks the use of the remote object in the client. When there are no more references to remote objects on the client, or if the reference "lease" expires and there is no update, the server will garbage reclaim the remote object.
However, we now have the-XX:+DISABLEEXPLICITGC configuration on the JVM boot parameters, so this thread is only soy sauce.

Idleremoverjboss The JBoss connection pool has a minimum value, which is awakened by JBoss every once in a while to check and destroy idle and invalid connections in the connection pool until the remaining number of connections is less than or equal to its minimum value.
 
java2d DISPOSERJVM   This thread primarily serves the various components of AWT. Before talking about the main job responsibilities of this thread, we need to introduce the Disposer class. Disposer provides a AddRecord method. If you want to do some cleanup before an object is destroyed, you can call the Disposer#addrecord method, pass the object and a custom Disposerrecord interface implementation class, and enter it to register.    the
          disposer class evokes "java2d disposer" threads, The thread scans whether the registered objects are being reclaimed, and if so, calls the Dispose method within the Disposerrecord implementation class for that object.  
          disposer is actually not limited to the AWT application scenario, Many of the components in AWT require access to many operating system resources, so these components need to be released before they are recycled.
 

quartzschedulerthreadquartz   Insttoolcachescheduler_quartzschedulerthread is the main thread of quartz, which is responsible for getting the trigger to be triggered at the next point in time, and then executing the trigger-associated job.   The
         principle is roughly as follows:  
          spring and quartz are used in conjunction with a scenario where the spring IOC container is initialized to create and initialize the quartz thread pool (treadpool) and start it. Each thread in the thread pool is waiting when it starts, waiting for the outside world to assign runnable (the thread holding the Job object). &NBSP
         Then initializes and starts the main thread of the quartz (insttoolcachescheduler_ Quartzschedulerthread), the thread will be in a wait state since it was started. After waiting for the signal to be given to the outside world, the Run method of the main thread actually begins to work. Run will get jobstore the next job to be triggered, will wait until the job's true trigger time, and then wrap the job as a Jobrunshell object (the object implements the Runnable interface, In fact, it is the top treadpool waiting for the outside assigned to his runnable), and then the newly created Jobrunshell to the thread pool, the thread pool is responsible for the execution of the job.   After the
thread pool receives runnable, it starts runnable from thread pooling, and reflection calls the Run method in Jobrunshell, and after the Run method executes, Treadpool reclaims the thread into the idle thread.

Insttoolcachescheduler_worker-2quartz The insttoolcachescheduler_worker-2 thread is a simple implementation of the threadpool thread, which is primarily responsible for allocating thread resources to execute
The Insttoolcachescheduler_quartzschedulerthread thread gives it the dispatch task (that is, Jobrunshell).

Jbosslifethreadjboss  The JBoss main thread starts successfully, the Jbosslifethread thread is instantiated after the application is deployed, and the start,jbosslifethread thread is waiting after it is successfully started to keep the JBoss Java process alive. The more popular point is that after the JBoss startup process has been executed, why is it not over? It is because there is this thread that hold the master. Cow B Bar ~ ~

JBoss System Threads (1) -1jboss The thread is a socket service, the default port number is: 1099. Primarily used to receive external naming service (Jboss JNDI) requests.

JCA Poolfillerjboss This thread primarily provides hosting of connection pooling for JBoss internal. A brief introduction to how it works:
Any class that has a remote connection requirement within JBoss needs to implement the Managedconnectionfactory interface, such as the one that needs to do the JDBC connection.
Xamanagedconnectionfactory the object, the interface is implemented. It then wraps the Xamanagedconnectionfactory object, along with other information, into the Internalmanagedconnectionpool object,   The Internalmanagedconnectionpool is then handed over to the queue within the Poolfiller object for management. The JCA Poolfiller thread periodically determines whether there are Internalmanagedconnectionpool objects in the queue that need to be created and managed, and if so, invokes the Filltomin method of the object, triggering it to create the appropriate remote connection. and maintain the connection to its corresponding connection pool.

JDWP Event Helper THREADJVM
JDWP is a communication interaction protocol that defines the format in which information is passed between the debugger and the program being debugged.  It defines the request command, the response data and the error code in detail, ensuring that the JVMTI and JDI of the front and back end are communicated smoothly. The thread is primarily responsible for mapping the JDI event into a JVMTI signal for the purpose of manipulating the JVM during debugging.


JDWP Transport LISTENER:DT_SOCKETJVMThis thread is a Java Debugger listener thread responsible for handling the client's debug requests. Usually we are accustomed to setting its listening port to 8787.
Low Memory DETECTORJVMThis thread is responsible for detecting the memory that can be used and allocating new memory space if the available memory is found to be low.
Process REAPERJVMThe thread is responsible for performing an OS command line operation.
Reference HANDLERJVMThe JVM creates the reference handler thread after the main thread is created, with the highest precedence of 10, which is primarily used to handle garbage collection issues that refer to the object itself (soft, weak, and virtual).
Surrogate Locker Thread (CMS) JVMThis thread is primarily used in conjunction with the CMS garbage collector, which is a daemon thread that is primarily responsible for handling GC processes where the Java layer's reference (referred to as soft references, weak references, and so on) is synchronized with the state of the object at the internal level of the JVM. Here's a little introduction to their implementation: Here's an example of Weakhashmap, with some key points listed first (we'll all string together these key points later):
1. We know that HashMap uses entry[] arrays to store data, Weakhashmap is no exception, and there is a entry[] array inside.
2. The entry of Weakhashmap is very special, its inheritance architecture is entry->weakreference->reference.
3. Reference has a global lock object: Lock, which is also known as Pending_lock. Note: It is a static object.
4. Reference has a static variable: pending.
5. Reference has a static inner class: The Referencehandler thread, which is initialized and started in the static block, waits in the wait state after the boot is complete, waiting in a lock synchronization lock module.
6. In addition, Weakhashmap inside also instantiated a referencequeue queue, the role of this queue, will be mentioned later.
7. The above key points are complete, and we'll string them up below.
Suppose that a reference to a lot of objects has been saved inside the Weakhashmap object. When the JVM is doing a CMS GC, it creates a concurrentmarksweepthread (CMST) thread to perform the GC, The Concurrentmarksweepthread thread is created at the same time that it creates a surrogatelockerthread (abbreviated SLT) thread and starts it, after SLT is started, in the wait phase. When Cmst starts the GC, a message is sent to SLT to get the global lock for the Java Layer Reference object: lock. Until the CMS GC is complete, the JVM will place the WeakReference container object belonging to all the reclaimed objects in Weakhashmap into the pending attribute of reference (after each GC is complete, The pending property is essentially not null), and then notifies SLT to release and notify the global lock: lock. At this point, the Run method of the Referencehandler thread is activated, leaving it out of the wait state and starting to work. Referencehandler This thread will move all WeakReference objects in the pending into their respective queues, such as the current weakreference belongs to a Weakhashmap object, Then it will be put into the corresponding Referencequeue queue (the queue is the list structure). The next time we get from the Weakhashmap object, put data, or call the size method, Weakhashmap will referencequeue in the queue WeakReference poll out and entry[] Data is compared, if found the same, it means that the entry saved objects have been GC off, then entry[] within the entry object removed.
TASKOBJECTTIMERFACTORYJVM As the name implies, this thread is used to perform the task. When we put a thought to the timer object and tell it the execution time, cycle time, the timer will put the task into the task queue, and notify the taskobjecttimerfactory thread to handle the task, The taskobjecttimerfactory thread removes a task that has a status of canceled from the task queue, and if the task is a non-repeating type of execution, it is removed from the task queue after the task has been executed, and if the task needs to be repeated, it calculates the point in time for the next execution.

VM Periodic task THREADJVM the thread that is the JVM's recurring Task Scheduler, created by Watcherthread, is a singleton object. This thread is used more frequently within the JVM, such as periodic memory monitoring, JVM health monitoring, and we often need to execute some JSTAT commands to view the GC, as follows:
Jstat-gcutil 23483 250 7 This command tells the JVM to print the PID at the console: 23483 for the GC case, which is printed at intervals of 250 milliseconds and printed 7 times altogether.

VM THREADJVMThis thread compares cow B, which is the thread matrix inside the JVM, According to the note in the Hotspot source code (VMTHREAD.HPP), it is a singleton object (the most primitive thread) that produces or triggers all other threads, and this single VM thread is used by other threads to do some VM operations (such as cleaning up garbage, etc.).
In the Vmthread structure there is a vmoperationqueue queue, all VM threading Operations (vm_operation) are saved in this queue, vmthread itself is a thread, its thread is responsible for executing a self-polling loop function ( Refer to: VMThread.cpp void Vmthread::loop ()), the loop function takes precedence from the Vmoperationqueue queue to take out the Action object (vm_operation) that is currently required, and calls the VM The _operation->evaluate function executes the business logic of the operation type itself.
The PS:VM operation type is defined in the Vm_operations.hpp file and is listed in several ways: Threadstop, Threaddump, Printthreads, Gencollectfull, Gencollectfullconcurrent, Cms_initial_mark, Cms_final_remark ..... Interested students, you can go to view the source files.
(transported from http://blog.csdn.net/a43350860/article/details/8134234 thanks to the original author)

2. Jmap
2.1 Gets the details of the memory allocation for running the Java program. such as the number of instances, size, etc.

2.2 Name Row format
jmap [option] pid
jmap [option] executable core
jmap [option] [[Email Protected]]remote-hostname-or-ip

-dump:[live,]format=b,file=<filename> uses the Hprof binary form to output the JVM's heap content to File =. The live sub-option is optional, and if you specify the live option, only the live object is exported to the file.
-finalizerinfo prints information about objects that are waiting to be reclaimed.
-heap prints the summary of the heap, the algorithm used by the GC, the configuration of the heap, and the use of the wise heap.
-histo[:live] Prints the number of instances per class, memory consumption, class full name information. The internal class name of the VM is prefixed with "*". If the live child parameter is added, only the number of live objects is counted.
-permstat Prints the classload and JVM heap for a long layer of information. Contains the name of each classloader, the liveliness, the address, the parent ClassLoader, and the number of classes loaded. In addition, the number of internal strings and the amount of memory consumed are also printed.
-F coercion. Use the-dump or-histo parameters when the PID is not appropriate. In this mode, the live sub-argument is invalid.
-H | -HELP Printing Auxiliary Information
-j Pass parameters to Jmap-initiated JVM.

2.3 Examples of Use
Jmap-histo pid (view instance)
Jmap-j-d64-dump:live,format=b,file=heap_dump.bin pidjmap-dump:format=b,file=heap.bin pid (export memory, said to have an impact on performance, use caution)
(Format=b is the binary meaning, but can not export text files I did not find, know to tell me)
The memory structure is all dump into the binary file, and the memory structure can be analyzed by IBM's Heapanalyzer and Eclipse's Memoryanalyzer.
This is the memory structure of our daily, which I looked at with Heapanalyzer, and we have listed the possible problems. (This tool I am not familiar with, for your reference only) Here's what I'm using Eclipse's memoryanalyzer to look at the memory map above is the Eclipse Analytics memory leak analysis. This feature is a lot of points. Can learn slowly


3. Jstat
3.1 This is a more practical command, you can observe CLASSLOADER,COMPILER,GC related information. Ability to monitor resources and performance at all times

3.2 Command format
-class: Statistics class loader behavior information
-compile: Statistical compilation Behavior Information
-GC: Statistics on JDK GC time heap information
-gccapacity: Statistics of different generations (do not know how to translate well, including the new district, old age area, Permanent district) corresponding heap capacity situation
-gccause: Statistical GC case, (same as-gcutil) and event that caused GC
-gcnew: When statistics GC, the Cenozoic situation
-gcnewcapacity: When statistics GC, the Cenozoic heap capacity
-gcold: Statistics GC, the situation of the elderly area
-gcoldcapacity: When statistics GC, the old area heap capacity
-gcpermcapacity: When statistics GC, permanent area heap capacity
-gcutil: When statistics GC, heap condition

3.3 Output parameter Contents
Percentage of space used in Survivor space zone 0 on S0-heap
S0c:s0 the size of the current capacity
S0u:s0 already used size
Percentage of space used in Survivor space Zone 1 on S1-heap
S1c:s1 the size of the current capacity
S1U:S1 already used size
Percentage of space used in Eden space on E-heap
Ec:eden Space Current capacity size
Size of Eu:eden space already used
The percentage of space used in the old area on the O-heap
Oc:old Space Current capacity size
Size of ou:old space already used
Percentage of space already used in the P-perm space area
Oc:perm Space Current capacity size
Size of ou:perm space already used
ygc-number of young GC occurrences from application boot to sample
ygct– the time (in seconds) used by the young GC when booting from the application to sampling
fgc-the number of full GC occurrences from application startup to sampling
fgct– time (in seconds) for full GC from application boot to sampling
gct-the total amount of time (in seconds) used for garbage collection from application startup to sampling, its value equals YGC+FGC Example 1 Example 2 (5 consecutive) Example 3 (PGCMN shows the minimum perm memory usage, PGCMX shows the maximum memory usage of perm, The PGC is the current newly generated perm memory footprint, the PC is but the front perm memory footprint) This tool has a lot of parameters, it is said that basically can cover all the functions of jprofile and other charge tools. Multi-use is very helpful for system tuning.


Note 1: We use the-f parameter when we use this command in daily. Because our users are not users of the start command
Note 2:daily These commands do not seem to be configured in the environment variables, this is what I see in my application machine. Need to go under the JDK directory to execute. Sudo is a must, of course.References:Remember, jstack, check for a deadlock.The principle and solution of the deadlock problem of Java programjstack (view threads), Jmap (view memory), and Jstat (profiling) commands

Java Multithreading: Deadlock

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.