# jstack

## About

`jstack` is a JDK utility used to generate thread dumps of a Java process. A thread dump contains a snapshot of all the threads running in the Java Virtual Machine (JVM) at a given time. It is useful for diagnosing issues like deadlocks, high CPU usage, thread contention, or long-running threads.

## **Key Use Cases**

* Identifying thread contention and deadlocks.
* Debugging threads stuck in infinite loops or blocking states.
* Understanding CPU-bound threads or hung processes.

## **Steps to Use jstack on Mac**

### **1. Find the Process ID (PID):**

* Open the terminal and use the `jps` command to list all Java processes:

```bash
jps
```

Output example:

<figure><img src="https://3632859567-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPd6ktrA5pPLsZJktj2fm%2Fuploads%2F2XHtlRnnE6LjemspfBnr%2Fjstack-1.png?alt=media&#x26;token=072ceb8d-e6d2-4ecc-8bf2-3756be9c959d" alt="" width="369"><figcaption></figcaption></figure>

Start the Java Application (here it is sample-print-service maven springboot application)

<figure><img src="https://3632859567-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPd6ktrA5pPLsZJktj2fm%2Fuploads%2F9Y3hMul4YloUNZjMywbg%2Fjstack-2.png?alt=media&#x26;token=073748fa-a66c-4de8-8d4c-83b8b70b8389" alt="" width="563"><figcaption></figcaption></figure>

`jps` command output is below

<figure><img src="https://3632859567-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPd6ktrA5pPLsZJktj2fm%2Fuploads%2FW8QNCCZIRKfUPB9nwD0f%2Fjstack-3.png?alt=media&#x26;token=9bedb4aa-41cd-4580-b688-954ef29d38eb" alt="" width="375"><figcaption></figcaption></figure>

Here, `83322` is the PID of our Springboot app.

### **2. Generate a Thread Dump:**

* Run the `jstack` command with the PID to generate a thread dump:

```bash
jstack 83322 > thread-dump.txt
```

This saves the thread dump to a file named `thread-dump.txt` in the current directory.

<figure><img src="https://3632859567-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPd6ktrA5pPLsZJktj2fm%2Fuploads%2FU0ITDdhPnslyioRmttiv%2Fjstack-4.png?alt=media&#x26;token=e82fe71b-d4a5-4939-9e82-c65fca9a4477" alt="" width="563"><figcaption></figcaption></figure>

{% file src="<https://3632859567-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FPd6ktrA5pPLsZJktj2fm%2Fuploads%2Fl32rFqEm31cOmXZaoqzT%2Fthread-dump.txt?alt=media&token=98b636ed-c3a4-4678-af9f-11e932b6a4d6>" %}

### **3. Analyze the Thread Dump:**

* Open the `thread-dump.txt` file and look for:
  * `BLOCKED` or `WAITING` states indicating thread contention.
  * Deadlock information, which is explicitly mentioned if detected.
  * Long-running threads consuming resources.
