AppPerfect Java Profiler 


Tutorial : Monitor Contention Detection.

This tutorial provides instructions on how to use AppPerfect Java Profiler product for detecting monitor contention and possible race conditions in a java application. This tutorial assumes you have successfully downloaded and installed AppPerfect DevTest4J on your machine with the default options.

This document is divided into following sections

  1. Creating Common Project
  2. AppPerfect Java Profiler

Within each section, multiple exercises are listed. All exercises assume you have installed the product in C:\AppPerfect\DevTest folder and will be referred as DEVTEST_HOME henceforth in tutorial. If you have installed the product in some other folder, modify the instructions below appropriately.

For this tutorial, create a java file called 'MonitorContention.java' copy-pasting the code shown below and compile it.


import java.io.*;

public class MonitorContention
{
    private static final int queue_size = 1000;
    private Object[]  queue = new Object[ queue_size ];
    private int       head  = 0;
    private int       tail  = 0;

    public synchronized void  enqueue( Object item )
    {
        head %= queue_size;
        queue[++(head)]= item;
        this.notify();                  // The "this" is there only to
    }                                   // improve readability.
    public synchronized Object  dequeue( )
    {
        try
        {
            if( head == tail ) // <=== This is a bug
            {
                long startTime = System.currentTimeMillis();
                System.out.println("waiting...");
                this.wait();
                System.out.println("waiting... time=" + (System.currentTimeMillis() - startTime)/1000);
            }
        }
        catch( InterruptedException e )
        {
            // If we get here, we were not actually notified.
            // returning null does not indicate that the
            // queue is empty, only that the waiting was
            // abandoned.
            return null;
        }
        tail %= queue_size;
        return queue[++(tail) ];
    }

    public static void main(String[] args) throws Exception
    {
        MonitorContention contention = new MonitorContention();
        InputStreamReader console = new InputStreamReader(System.in);
        Thread.sleep(2000);
        createMonitorContentionThread(contention, 8).start();
        createMonitorContentionThread(contention, 12).start();
        Thread.sleep(5000);
        System.out.println("Release ONE");
        createReleaseThread(contention, 2).start();
        Thread.sleep(9000);
        System.out.println("Release TWO");
        createReleaseThread(contention, 2 + 8 + 12).start();
        System.out.print("Press any key to continue...");
        console.read();
        console.read();
    }
    static int count = 0;
    public static Thread createMonitorContentionThread(final MonitorContention contention, final int enqueCount)
    {
        final int th_id = count++;
        return new Thread(new Runnable()
        {
            public void run()
            {
                try
                {
                    for(int i = 0; i < 2 + (enqueCount/2); ++i)
                    {
                        contention.enqueue(new Object());
                    }
                    System.out.println("Waiting for 5 sec. [" + th_id + "]");
                    for(int i = 0; i < enqueCount; ++i)
                    {
                        contention.dequeue();
                        System.out.println("Waiting for 0.1 sec. [" + th_id + "]");
                        Thread.sleep(100);
                    }
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
    }

    public static Thread createReleaseThread(final MonitorContention contention, final int dequeCount)
    {
        final int th_id = count++;
        return new Thread(new Runnable()
        {
            public void run()
            {
                try
                {
                    for(int i = 0; i < dequeCount; ++i)
                    {
                        contention.enqueue(new Object());
                    }
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
    }
}

Creating Common Project

Exercise 1: Launch AppPerfect DevTest4J

Action:

  1. Click on Start -> Programs ->AppPerfect DevTest4J x.x.x -> AppPerfect DevTest4J
  2. On launching AppPerfect DevTest4J a Welcome page will be displayed. Go through the brief description given for each product and click on the product icon to view its perspective.
    NB: Welcome page is displayed only when DevTest4J x.x.x is launched and last time no project was opened.
  3. To switch between different product perspectives click on corresponding project button in toolsbar.

Exercise 2: Creating a Common Project

Action:

  1. Launch the Common Project Wizard by clicking File ->New... menu option. The New Project wizard will be launched.
  2. Go through the instruction provided on top of the General tab.
  3. Keep the default project name and location for the purpose of this exercise. We don't have to provide "Notification" settings or "Remote Application/AppServer" settings for this exercise. Click on the Next button.
  4. In the Source tab provide the location of source file "RaceCondition.java". Click the Next button.
  5. Use the default JDK which is bundled with AppPerfect DevTest4J and click on the Next button.
  6. In the "Environment" tab provide the location of "RaceCondition.class" file.
  7. Click on "Verify Classpath" button to validate the classpath.
  8. Classpath validation dialog will be launched and the classpath will be verified. A message saying that the classpath specified is correct should be displayed. Click on the "OK" button. Click on the Next button.
  9. In the "Target" tab select project type as "LOCAL".
  10. For working folder provide the path to the folder containing the the "RaceCondition.class" file.
  11. Specify the Main Class as "RaceCondition".
  12. Select the "Launch target application automatically" checkbox. Click on the Finish button.
  13. A confirmation message saying that the project is saved will be displayed. Click on the OK button.

AppPerfect Java Profiler

NB:Please follow the steps provided in the "Creating Common Project" section to first create a common project, then proceed further.

Exercise 1: Define a Java Profiler project

Action:

  1. Once the common project is successfully created another dialog - Define Project Properties dialog - will be displayed.
  2. Read the instructions at top of each tab.
  3. Go through the descriptions for Profiling Types. Keep the default Development Mode Profiling and select Profiling Options tab.
  4. Study the descriptions of the three profiling options. You can configure Filters using Configure Filters option.Use default values.
  5. Study the descriptions of Instrumentation Options. Use the default: Dynamic Instrumentation enabled.
  6. Study the changes indicated in the Launch Instructions tab. AppPerfect Java Profiler must modify your application server's startup file to add instructions to load the profiling agent, etc. This tab shows the exact changes that needs to be made to the startup script. AppPerfect Java Profiler understands how to configure startup scripts for most commonly available application servers. Also, since it does not modify the original file and instead makes a copy to store the modifications, it is almost always desirable to let AppPerfect Java Profiler make the changes. Click OK button.
  7. Click through all the menu items to familiarize yourself with the available features and how to access them.
  8. Click on Tools ->Options... menu item. Click on the JDKs tab and ensure that the JDK path has been set correctly. This is the path provided for JDK during installation of AppPerfect DevTest4J. You may modify the path or add new JDK through this dialog box. It is critical that a correct version of JDK is available for AppPerfect DevTest4J to perform correctly.
  9. Click Help -> Table of Contents menu item to see AppPerfect DevTest4J product documentation.

Exercise 2: Start Profiling

Action:

  1. To start profiling click on Project -> Run from the menubar.
  2. A progress message will be shown while target application is launched.
  3. Observe the dynamic updation of data in the default (Summary) view. You can see various profiling metrics such as heap memory usage, object instance count and Thread count.
  4. From the Navigational Tree select Monitors node.
  5. On the right hand side, in the monitors tab you will see that there are 3 wait counts on the particular monitor and that the wait duration is inecreasing.
  6. Double click on row having Monitor ID 1; in the Details tab, and you will see that Thread-0 and Thread-1 waited on the same monitor at the same time for the same amount of duration. This is a sign of a possible race condition. Also you will see that Thread-1 again waits for a longer duration this time indicating a high monitor contention.
  7. Stop Profiling by selecting Project -> Stop.
  8. Click Yes to stop profiling.
  9. Click No to collect information from the target application.