10 Testing and Profiling Java Application Projects

JDeveloper provides a suite of tools for analyzing the quality and performance of your Java code. Use these tools to improve both the quality of your code and your own programming skills.

This chapter includes the following sections:

10.1 About Profiling Applications

The profiler gathers statistics on a running program that enable you to diagnose performance issues and correct code inefficiencies.

The following profiling capabilities are available:

  • Telemetry—monitors CPU, memory usage, number of threads and loaded classes. See Profiling Telemetry.

  • Methods—profiles methods execution times and invocation count, including call trees. See Profiling Methods.

  • Objects—profiles size and count of allocated objects including allocation paths. See Profiling Objects.

  • Threads-—profiles threads time and state. See Profiling Threads.

  • Locks—profiles locks content data. See Profiling Locks.

10.2 About Starting the Profiler

JDeveloper provides the following pathways for starting the profiler:

10.3 Starting and Profiling JDeveloper Applications Simultaneously

You may simultaneously start a JDeveloper application and the profiling of that application by following these steps:

  1. Choose Run > Profile Project
  2. On the main window click the Configure Session button and select a profiler mode by clicking on it. You can change the profiler mode at any point by clicking the Profile drop down arrow.
  3. On the main window, click the Profile button.

    The application and the profile session are simultaneously started.

10.4 Attaching the Profiler to a Running JDeveloper Applications

You may profile a JDeveloper project that is already running by following these steps:

  1. Choose Run > Attach to Project
  2. On the main window click the Configure Session button and select a profiler mode by clicking on it. You can change the profiler mode at any point by clicking the Profile drop down arrow.

    If the target application is running outside JDeveloper, select the Setup attach to project target and make the appropriate selections in the Attach Settings window. For more information on profiling external applications, see Profiling External Applications

  3. On the main window, click the Attach button.

    A profile session tracking the running application is started.

10.5 Profiling External Applications

You may profile an application that is not started from within the JDeveloper IDE by following these steps:

  1. Choose Run > Attach to External Process

    The Profiling External Process tab opens in the main window.

  2. Click the Configure Session button and select Setup attach to process

    The Attach Settings window appears.

  3. Select the type of application to be profiled from the Profile drop-down menu and select the process to be profiled. The Attach Settings window explains and provides detailed instructions for each option. Click OK.
  4. On the main window click the Configure Session button and select a profiler mode by clicking on it. You can change the profiler mode at any point by clicking the Profile drop down arrow.
  5. Click the Attach button.

    A profile session tracking the selected application is started.

10.6 Profiling Telemetry

The telemetry mode provides the following metrics:

CPU and GC—displays the CPU and GC percentage of use at a given time

Memory—displays in MB the heap size and used heap at a given time

Surviving Generations —displays the number of surviving generations at a given time. It also displays indicates the GC intervals

Threads and Classes—displays number of loaded classes and threads at a given time

To start a profiling telemetry session, see "About Starting the Profiler"

Figure 10-1 shows a snapshot of a telemetry session

Figure 10-1 Telemetry Session

Profiling telemetry snapshot

10.7 Profiling Methods

The methods mode provides metrics for methods and classes. The methods report allows you to view the data by Forward Calls, Hot Spots, and Reverse Calls by clicking on the appropriate icons. You may also choose to Show Delta Values and Select Threads.
  • Show Delta Values-this action switches from absolute values to incremental values. The values displayed prior to switching the view are remembered but the new view displays changes starting at the moment the new selection was made. Clicking this icon again resets the results back to absolute values.

  • Select Threads-this action shows threads available in live results or a saved snapshot and allows you to select specific threads for displaying results. This feature is especially useful when tracking EDT slowness in desktop applications or analyzing worker threads in server applications. The Merge selected threads option is enabled if some of the threads are selected and it is disabled for the Show all threads option. This feature merges results from the selected threads to a single tree.

Additionally, you may select the columns to be displayed; the options are Total Time, Total Time (CPU), Selected, and Hits/Invocations (depending on the session configuration).

To start a profiling methods session, see "About Starting the Profiler"

Figure 10-2 shows a snapshot of a methods session.

Figure 10-2 Methods Session

Sample mrthod session snapshot

10.7.1 Profiling Specific Methods

You may narrow down the scope of the methods session to profile specific methods or classes by following these steps:

  1. Click on the Icon to display profiling settings baricon.

    A new settings bar appears.

  2. On the Profile dropdown make the appropriate selection.
  3. Click the Plus icon to add a class or method.

    The Select Class or Select Method window appears.

  4. To select a class in the Select Class window, choose the Project, Package, and Class and click OK.

    To select a method in the Select Method window, choose the Project, Package, Class and Method and click OK

    Alternatively, you may right click on a method or a class to select it. This feature is available in the profile results and snapshot windows.

10.8 Profiling Objects

The objects mode provides a list of classes allocated to a project including live instances and bytes allocation. By clicking the Click to select classes icon on the top-right corner of the page you access a drop-down menu that allows you select the classes to be profiled. The All Classes mode shows all classes and object that are live on the Virtual Machine heap. The Project Classes filter allows to view only the classes defined in the project.

To start a profiling objects session, see "About Starting the Profiler"

Figure 10-3 shows a snapshot of an Objects session

Figure 10-3 Objects Session

Objects session snapshot displaying list of classes

10.8.1 Profiling Specific Objects

You may elect to profile specific classes by right clicking on a class and selecting Profile Class. The Track only live objects and Limit allocations depth checkboxes appear.

Track only live objects — when selected, it tracks only live objects. If not selected, it tracks all objects allocated by the application.

Limit allocations depth — limits the stack depth allocations to the number specified.

After selecting a class, click the Apply button on the right while the profiling session is in progress to submit your changes. This action clears the view to display only the classes that you selected as shown in Figure 10-4

Figure 10-4 Objects Session - Selected Classes View

Snapshot of a selected class profile

10.9 Profiling Threads

The threads mode allows you to view detailed information about application thread activity.

To start a profiling threads session, see "About Starting the Profiler"

Figure 10-5 shows a snapshot of a threads session

Figure 10-5 Threads Session

Sample application threads session

Additionally, you may customize the threads you monitor by accessing the Live Threads drop-down list and choosing from the available options: All Threads, Live Threads (Default), Finished Threads, and Selected Threads.

10.10 Profiling Locks

The locks mode allows you to view details about locked threads and the threads that are monitoring and holding locks.

To start a profiling locks session, see "About Starting the Profiler"

Figure 10-6 shows a snapshot of a locks session

Figure 10-6 Locks Session

Profiling locks session screen

In the session window you can choose Threads or Monitors in the Threads drop-down list. Choose Threads to view locked threads. Expand the nodes to view the owners of the locks. Choose Monitors to view the threads that are locking other threads.

10.11 Additional Functions when Running a Profiling Session

While the profiler session is in progress, additional actions related to the actual profiler mode are available in the toolbar of the profiler window. The following actions are always available:

Thread dump—creates a textual dump of all active threads and monitors of the profiled application. It shows what methods have been executed at the point of capturing the dump, thread by thread. This information is useful to view what the application is currently doing. The thread dump also contains information about locks, threads holding the locks, and threads waiting to acquire a lock. This data is essential when debugging deadlocks. To capture a Thread Dump, click the Thread Dump icon during the profiling session. To learn more about taking snapshots, see Taking and Accessing Snapshots of Profiling Data

Heap dump—saves an image of the current heap content of the profiled process in .hprof format and optionally opens it in heap browser. For more information, see Capturing Heap Dump Data

GC—requests the JVM of the profiled process to invoke garbage collection. The JVM behavior for garbage collection is not defined in the JVM specification. It should do the garbage collection at some point, but there is no guarantee it will do it immediately or at all.

Additionally, when profiling Methods or Objects, the following actions are available:

Snapshot—creates a snapshot of all currently collected profiling data related to methods or objects. The snapshot opens in a separate window and can be saved to the project or to an external file. For more information, see Taking and Accessing Snapshots of Profiling Data

Reset collected results—clears all currently collected profiling data related to methods or objects.

The other actions displayed in the toolbar of the profiler window are specific to the actual profiling mode. If multiple profiling modes are active in a profiling session, the toolbar displays actions available for the currently displayed modes.

10.12 Capturing Heap Dump Data

You can take a heap dump when a profiling session is in progress. When you take a heap dump you are prompted to save the heap to your project or local file system. After you save a heap dump you can load the heap dump at any time and browse the objects on the heap, locate references to individual objects and compare heap dumps to view the differences between the snapshots. You do not need to have a running profiling session to load and browse the heap dump.

The application must be running on JDK 1.5.0_12 or higher to take a heap dump.

To take a heap dump using a profiling point:

  1. Open the source file containing the code where you want to place the profiling point.

  2. Right-click in the line of code where you want to place the profiling point and select Add Profiling Point.

  3. In the Profiling Point Type list, select one of the following snapshot options and click Next:

    • Take Snapshot

    • Timed Take Snapshot

    • Triggered Take Snapshot

  4. In the Customize Properties page of the wizard, select Heap Dump as the type of snapshot and modify any additional settings. The Heap Dump option is available under Settings > Take.

When you use a profiling point to take a heap dump, you specify the point in your source code where you want to place the profiling point. For example, you may want to take a heap dump when a thread enters a specific method.

To take a heap dump on OutOfMemory error:

  1. From the Main menu, select Tools > Preferences > Profiler.
  2. In the On OutOfMemoryError list, select an option from the drop-down list to specify what the IDE does when an OutOfMemoryError is encountered.

    The default behavior is to save the heap dump to the profiled project.

10.12.1 Viewing UI Elements with Heap Walker

The heap dump viewer (Heap Walker) displays logical values of objects such as String value, File path, URL address, etc. In addition, it also provides a visual snapshot of UI attributes and elements such as Color, Font, Button, etc.

For most classes and instances represented in the heap dump, the textual and numerical properties are adequate for describing and examining data structures and for discovering bugs such as memory leaks, inefficient memory usage and others. However, for many types of objects, the in-memory representation is not suited for quickly determining what the object is.

The visual representation feature is ideal for examining UI elements, where displaying object properties is not precise enough to aid users in identifying the exact location of the application UI. For example, by just reading position, size and references to nested elements of an UI container the user may not realize that an object may represent an Open File dialog created by the application.

Access the image representation of a heap dump element by browsing through the instance of a given class. Figure 10-7 shows Heap Walker panels including a visual preview of the application window at the point when the heap has been dumped.

Figure 10-7 Heap Walker - Image Preview

Image preview

10.12.1.1 Image Preview Use Cases

The Heap Walker image preview is useful in the following use cases:

  • Identifying selected UI element. Browse instances of the desired type when you need to find a particular UI element like Button, Label, etc

  • Determining application state at the time of dumping the heap. Bugs reported by users often do not contain all the necessary information or miss important details. By displaying the application UI users can immediately see that for example a text document was being loaded when an out of memory exception was thrown.

  • Searching for UI snippets unintentionally kept in memory. Parts of the UI are sometimes not being released from memory, which can cause serious problems given that tables, trees or editors often reference very large data models. By browsing for example Panel elements users can easily discover these snippets, realize how much memory is being wasted and identify the problem preventing the UI from being released.

  • Discovering duplicities. By browsing Images, for example, users can immediately see multiple instances of the same image being allocated in memory, which is a waste of resources.

  • Offline UI analysis. Heap Walker is able to recreate the UI structure from a heap dump. This way an UI developer can analyze the UI building blocks without access to the actual application, which could be running on a different and incompatible system

It is important to note the following exceptions to the Image Preview function:

  • No support for viewing tree data.

  • Foreground, background or font attributes may not show on certain implementations.

  • Custom controls cannot be displayed.

  • UI text for certain elements may not fully display in the Instance view.

10.12.2 How to Analyze a Heap Dump Using Object Query Language (OQL)

OQL is a SQL-like query language to query a Java heap that enables you to filter/select information wanted from the Java heap. While pre-defined queries such as "show all instances of class X" are already supported by the tool, OQL adds more flexibility. OQL is based on JavaScript expression language.

When you load a Java heap in the Heap window, you can click the OQL Console tab of the window to open the OQL editor. The OQL Console contains an OQL editor, a saved OQL queries window and a window that displays the query results. You can use any of the sample OQL queries or create a query to filter and select heap data to locate the information that you want from the Java heap. After you choose or write a query, you can run the query against the Java heap and view the results.

An OQL query is of the following form:

select <JavaScript expression to select>
[ from [instanceof] <class name> <identifier>
[ where <JavaScript boolean expression to filter> ] ]

where class name is fully qualified Java class name (example: java.net.URL) or array class name. char[] (or [C) is char array name, java.io.File (or [Ljava.io.File;) is name of java.io.File[] and so on. Note that fully qualified class name does not always uniquely identify a Java class at runtime. There may be more than one Java class with the same name but loaded by different loaders. So, class name is permitted to be id string of the class object. If instanceof keyword is used, subtype objects are selected. If this keyword is not specified, only the instances of exact class specified are selected. Both from and where clauses are optional.

In select and (optional) where clauses, the expression used in JavaScript expression. Java heap objects are wrapped as convenient script objects so that fields may be accessed in natural syntax. For example, Java fields can be accessed with obj.field_name syntax and array elements can be accessed with array[index] syntax. Each Java object selected is bound to a JavaScript variable of the identifier name specified in from clause.

10.12.2.1 OQL Examples

Select all Strings of length 100 or more:

select s from java.lang.String s where s.count >= 100

Select all int arrays of length 256 or more:

select a from int[] a where a.length >= 256

Show content of Strings that match a regular expression:

select {instance: s, content: s.toString()} from java.lang.String s
    where /java/(s.toString())

Show path value of all File objects:

select file.path.toString() from java.io.File file

Show names of all ClassLoader classes:

select classof(cl).name 
    from instanceof java.lang.ClassLoader cl

Show instances of the Class identified by given id string:

select o from instanceof 0xd404b198 o

0xd404b198 is id of a Class (in a session). This is found by looking at the id shown in that class's page.

10.12.2.2 OQL built-in objects and functions

Heap object

The heap built-in object supports the following methods:

  • heap.forEachClass - calls a callback function for each Java Class

    heap.forEachClass(callback);
    
  • heap.forEachObject - calls a callback function for each Java object

    heap.forEachObject(callback, clazz, includeSubtypes);
    

    clazz is the class whose instances are selected. If not specified, defaults to java.lang.Object. includeSubtypes is a boolean flag that specifies whether to include subtype instances or not. Default value of this flag is true.

  • heap.findClass - finds Java Class of given name

    heap.findClass(className);
    

    where className is name of the class to find. The resulting Class object has following properties:

    • name - name of the class.

    • superclass - Class object for super class (or null if java.lang.Object).

    • statics - name, value pairs for static fields of the Class.

    • fields - array of field objects. field object has name, signature properties.

    • loader - ClassLoader object that loaded this class.

    Class objects have the following methods:

    • isSubclassOf - tests whether given class is direct or indirect subclass of this class or not.

    • isSuperclassOf - tests whether given Class is direct or indirect superclass of this class or not.

    • subclasses - returns array of direct and indirect subclasses.

    • superclasses - returns array of direct and indirect superclasses.

  • heap.findObject - finds object from given object id

    heap.findObject(stringIdOfObject);
    
  • heap.classes - returns an enumeration of all Java classes

  • heap.objects - returns an enumeration of Java objects

    heap.objects(clazz, [includeSubtypes], [filter])
    

    clazz is the class whose instances are selected. If not specified, defaults to java.lang.Object. includeSubtypes is a boolean flag that specifies whether to include subtype instances or not. Default value of this flag is true. This method accepts an optional filter expression to filter the result set of objects.

  • heap.finalizables - returns an enumeration of Java objects that are pending to be finalized.

  • heap.livepaths - return an enumeration of paths by which a given object is alive. This method accepts optional second parameter that is a boolean flag. This flag tells whether to include paths with weak reference(s) or not. By default, paths with weak reference(s) are not included.

    select heap.livepaths(s) from java.lang.String s
    

    Each element of this array itself is another array. The later array is contains an objects that are in the 'reference chain' of the path.

  • heap.roots - returns an Enumeration of Roots of the heap.

    Each Root object has the following properties:

    • id - String id of the object that is referred by this root

    • type - descriptive type of Root (JNI Global, JNI Local, Java Static, etc.)

    • description - String description of the Root

    • referrer - Thread Object or Class object that is responsible for this root or null

Examples

  • Access static field 'props' of class java.lang.System

    select heap.findClass("java.lang.System").statics.props
    select heap.findClass("java.lang.System").props
    
  • Get number of fields of java.lang.String class

    select heap.findClass("java.lang.String").fields.length
    
  • Find the object whose object id is given

    select heap.findObject("0xf3800b58")
    
  • Select all classes that have name pattern java.net.*

    select filter(heap.classes(), "/java.net./(it.name)")
    

Functions on individual objects

  • allocTrace function

    Returns allocation site trace of a given Java object if available. allocTrace returns array of frame objects. Each frame object has the following properties:

    • className - name of the Java class whose method is running in the frame.

    • methodName - name of the Java method running in the frame.

    • methodSignature - signature of the Java method running in the frame.

    • sourceFileName - name of source file of the Java class running in the frame.

    • lineNumber - source line number within the method.

  • classof function

    Returns class object of a given Java object. The resulting object supports the following properties:

    • name - name of the class

    • superclass - class object for super class (or null if java.lang.Object)

    • statics - name, value pairs for static fields of the class

    • fields - array of field objects. Field objects have name, signature properties

    • loader - ClassLoader object that loaded this class.

    Class objects have the following methods:

    • isSubclassOf - tests whether given class is direct or indirect subclass of this class or not

    • isSuperclassOf - tests whether a given class is direct or indirect superclass of this class or not

    • subclasses - returns array of direct and indirect subclasses

    • superclasses - returns array of direct and indirect superclasses

    Examples

    • Show class name of each Reference type object

      select classof(o).name from instanceof java.lang.ref.Reference o
      
    • Show all subclasses of java.io.InputStream

      select heap.findClass("java.io.InputStream").subclasses()
      
    • Show all superclasses of java.io.BufferedInputStream

      show all superclasses of java.io.BufferedInputStream 
      
  • forEachReferrer function

    Calls a callback function for each referrer of a given Java object.

  • identical function

    Returns whether two given Java objects are identical or not, for example:

    select identical(heap.findClass("Foo").statics.bar, heap.findClass("AnotherClass").statics.bar)
    
  • objectid function

    Returns String id of a given Java object. This id can be passed to heap.findObject and may also be used to compare objects for identity. For example:

    select objectid(o) from java.lang.Object o
    
  • reachables function

    Returns an array of Java objects that are transitively referred from the given Java object. Optionally accepts a second parameter that is comma separated field names to be excluded from reachability computation. Fields are written in class_name.field_name pattern.

    Examples

    • Print all reachable objects from each Properties instance.

      select reachables(p) from java.util.Properties p
      
    • Print all reachables from each java.net.URL but omit the objects reachable via the fields specified.

      select reachables(u, 'java.net.URL.handler') from java.net.URL u
      
  • referrers function

    Returns an enumeration of Java objects that hold reference to a given Java object. This method accepts optional second parameter that is a boolean flag. This flag tells whether to include weak reference(s) or not. By default, weak reference(s) are not included.

    Examples

    • Print number of referrers for each java.lang.Object instance

      select count(referrers(o)) from java.lang.Object o
      
    • Print referrers for each java.io.File object

      select referrers(f) from java.io.File f
      
    • Print URL objects only if referred by 2 or more

      select u from java.net.URL u where count(referrers(u)) > 2
      
  • referees function

    Returns an array of Java objects to which the given Java object directly refers to. This method accepts optional second parameter that is a boolean flag. This flag tells whether to include weak reference(s) or not. By default, weak reference(s) are not included. For example, to print all static reference fields of java.io.File class:

    select referees(heap.findClass("java.io.File"))
    
  • refers function

    Returns whether first Java object refers to second Java object or not.

  • root function

    If the given object is a member of root set of objects, this function returns a descriptive Root object describing why it is so. If given object is not a root, then this function returns null.

  • sizeof function

    Returns size of the given Java object in bytes, for example:

    select sizeof(o) from int[] o
    
  • retainedsize function

    Returns size of the retained set of the given Java object in bytes. Note: Using this function for the first time on a heap dump may take significant amount of time.

    The following is an example usage of the retainedsize function:

    select rsizeof(o) from instanceof java.lang.HashMap o
    
  • toHtml function

    Returns HTML string for the given Java object. Note that this is called automatically for objects selected by select expression. But, it may be useful to print more complex output. For example, to print a hyperlink in bold font:

    select "<b>" + toHtml(o) + "</b>" from java.lang.Object o
    

10.12.2.3 Selecting Multiple Values

Multiple values can be selected using JavaScript object literals or arrays.

For example, show the name and thread for each thread object

select { name: t.name? t.name.toString() : "null", thread: t } 
from instanceof java.lang.Thread t

array/iterator/enumeration manipulation functions

These functions accept an array/iterator/enumeration and an expression string [or a callback function] as input. These functions iterate the array/iterator/enumeration and apply the expression (or function) on each element. Note: JavaScript objects are associative arrays. So, these functions may also be used with arbitrary JavaScript objects.

  • concat function

    Returns whether the given array/enumeration contains an element the given boolean expression specified in code. The code evaluated can refer to the following built-in variables.

    • it - currently visited element

    • index - index of the current element

    • array - array/enumeration that is being iterated

    For example, to select all Properties objects that are referred by some static field some class:

    select p from java.util.Properties p
    where contains(referrers(p), "classof(it).name == 'java.lang.Class'")
    
  • count function

    Returns the count of elements of the input array/enumeration that satisfy the given boolean expression. The boolean expression code can refer to the following built-in variables.

    • it - currently visited element

    • index - index of the current element

    • array - array/enumeration that is being iterated

    For example, print the number of classes that have a specific name pattern:

    select count(heap.classes(), "/java.io./(it.name)")
    
  • filter function

    Returns an array/enumeration that contains elements of the input array/enumeration that satisfy the given boolean expression. The boolean expression code can refer to the following built-in variables.

    • it - currently visited element

    • index - index of the current element

    • array - array/enumeration that is being iterated

    • result -> result array/enumeration

    Examples

    • Show all classes that have java.io.* name pattern

      select filter(heap.classes(), "/java.io./(it.name)")
      
    • Show all referrers of URL object where the referrer is not from java.net package

      select filter(referrers(u), "! /java.net./(classof(it).name)")
      from java.net.URL u
      
  • length function

    Returns number of elements of an array/enumeration.

  • map function

    Transforms the given array/enumeration by evaluating given code on each element. The code evaluated can refer to the following built-in variables.

    • it - currently visited element

    • index - index of the current element

    • array - array/enumeration that is being iterated

    • result -> result array/enumeration

    Map function returns an array/enumeration of values created by repeatedly calling code on each element of input array/enumeration.

    For example, show all static fields of java.io.File with name and value:

    select map(heap.findClass("java.io.File").statics, "index + '=' + toHtml(it)")
    
  • max function

    Returns the maximum element of the given array/enumeration. Optionally accepts code expression to compare elements of the array. By default numerical comparison is used. The comparison expression can use the following built-in variables:

    • lhs - left side element for comparison

    • rhs - right side element for comparison

    Examples

    • Find the maximum length of any string instance

      select max(map(heap.objects('java.lang.String', false), 'it.count'))
      
    • Find string instance that has the maximum length

      select max(heap.objects('java.lang.String'), 'lhs.count > rhs.count')
      
  • min function

    Returns the minimum element of the given array/enumeration. Optionally accepts code expression to compare elements of the array. By default numerical comparison is used. The comparison expression can use the following built-in variables:

    • lhs - left side element for comparison

    • rhs - right side element for comparison

    Examples

    • Find the minimum size of any vector instance

      select min(map(heap.objects('java.util.Vector', false), 'it.elementData.length'))
      
    • Find vector instance that has the maximum length

      select min(heap.objects('java.util.Vector'), 'lhs.elementData.length < rhs.elementData.length')
      
  • sort function

    Sorts a given array/enumeration. Optionally accepts code expression to compare elements of the array. By default numerical comparison is used. The comparison expression can use the following built-in variables:

    • lhs - left side element for comparison

    • rhs - right side element for comparison

    Examples

    • Print all char[] objects in the order of size.

      select sort(heap.objects('char[]'), 'sizeof(lhs) - sizeof(rhs)')
      
    • Print all char[] objects in the order of size but print size as well.

      select map(sort(heap.objects('char[]'), 'sizeof(lhs) - sizeof(rhs)'),  '{ size: sizeof(it), obj: it }')
      
  • top function

    Returns top N elements of the given array/enumeration. Optionally accepts code expression to compare elements of the array and the number of top elements. By default the first 10 elements in the order of appearance is returned. The comparison expression can use the following built-in variables:

    • lhs - left side element for comparison

    • rhs - right side element for comparison

    Examples

    • Print 5 longest strings

      select top(heap.objects('java.lang.String'), 'rhs.count - lhs.count', 5)
      
    • Print 5 longest strings but print size as well.

      select map(top(heap.objects('java.lang.String'),  'rhs.count - lhs.count', 5), '{ length: it.count, obj: it }')
      
  • sum function

    Returns the sum of all the elements of the given input array or enumeration. Optionally, accepts an expression as second param. This is used to map the input elements before summing those.

    For example, return the sum of sizes of the reachable objects from each Properties object:

    select sum(map(reachables(p), 'sizeof(it)')) 
    from java.util.Properties p
     
    // or omit the map as in ...
    select sum(reachables(p), 'sizeof(it)') 
    from java.util.Properties p
    
  • toArray function

    Returns an array that contains elements of the input array/enumeration.

  • unique function

    Returns an array/enumeration containing unique elements of the given input array/enumeration.

    The following example selects a unique char[] instances referenced from strings. Note that more than one string instance can share the same char[] for the content.

    // number of unique char[] instances referenced from any String
    select count(unique(map(heap.objects('java.lang.String'), 'it.value')))
     
    // total number of Strings
    select count(heap.objects('java.lang.String'))
    

10.12.2.4 Other Examples

The following example prints a histogram of each class loader and number of classes loaded by it.

java.lang.ClassLoader has a private field called classes of type java.util.Vector and Vector has a private field named elementCount that is number of elements in the vector. The query selects multiple values (loader, count) using JavaScript object literal and map function. It sorts the result by count (i.e., number of classes loaded) using sort function with comparison expression.

select map(sort(map(heap.objects('java.lang.ClassLoader'), 
'{ loader: it, count: it.classes.elementCount }'), 'lhs.count < rhs.count'),
'toHtml(it) + "<br>"')

The following example shows the parent-child chain for each class loader instance.

select map(heap.objects('java.lang.ClassLoader'),
      function (it) {
         var res = '';
         while (it != null) {
            res += toHtml(it) + "->";
            it = it.parent;
         }
         res += "null";
         return res + "<br>";
      })

Note that the parent field of java.lang.ClassLoader class is used and the example walks until the parent is null using the callback function to map call.

The following example prints the value of all System properties. Note that this query (and many other queries) may not be stable - because private fields of the Java platform classes may be modified or removed without any notification (implementation detail). But using such queries on user classes may be safe, given that you have control over the classes.

select map(filter(heap.findClass('java.lang.System').props.table, 'it != null && it.key != null && it.value != null'),
            function (it) {
                var res = it.key.toString() + ' = ' + it.value.toString();
                return res;
            });
  • java.lang.System has static field by name 'props' of type java.util.Properties.

  • java.util.Properties has field by 'table' of type java.util.Hashtable$Entry (this field is inherited from java.util.Hashtable). This is the hashtable buckets array.

  • java.util.Hashtable$Entry has key, value and next fields. Each entry points the next entry (or null) in the same hashtable bucket.

  • java.lang.String class has a value field of type char[].

10.13 Taking and Accessing Snapshots of Profiling Data

A snapshot captures profiling data at a specific point in time and allows you to access them via the Snapshot window. See Accessing Snapshots

A snapshot differs from live profiling results in the following ways:

  • Snapshots can be examined when no profiling session is running.

  • Snapshots can be easily compared.

There are two options for taking snapshots:

10.13.1 Taking Snapshots at the End of a Profiling Session

When closing a profiled application, or if it finishes on its own, while the profiling session is in progress, the profiler asks you whether to take a snapshot of the results collected so far by displaying the Application Finished dialog.

Figure 10-8 Application Finished Dialog

Confirmation dialog asking whether to take a snapshot of the results collected so far.

Click Yes to save the snapshot.

10.13.2 Taking Snapshots During a Profiling Session

You may take a snapshot of the profiling data at any time during the profiling session by clicking the Snapshot icon shown in the figure below.

Figure 10-9 Snapshot Icon

Screenshot, depicting the Snapshot icon.

To control how the snapshots functionality behaves during a session, go to Tools > Preferences > Profiler and click the When taking snapshots drop-down menu to see the following options:

Open New Snapshot—it opens the snapshot right after clicking the Snapshot icon

Save New Snapshot—it saves a new snapshot every time you click the Snapshot Icon

Open and Save New Snapshot—it saves and opens a snapshot right after clicking the Snapshot icon.

You may take multiple snapshots during a profiling session and you will also be prompted to save a "final" snapshot at the end of the session.

10.13.3 Starting and Stopping the Application Finished Dialog

When the Application Finished dialog appears at the end of the profiling session, if you select the Do not show this message again checkbox the dialog would not display again. If at a later time you want to reactivate the display of this dialog, go to Tools > Preference > Profiler and click Reset button as shown in the figure below.

Figure 10-10 Reset Button in the Profiler Preferences Dialog

Reset button for display settings of the Application Finished dialog.

10.13.4 Accessing Snapshots

You may access you profiling session snapshots by going to Windows > Profiling > Snapshots. The Snapshots window appears as shown in the figure below.

Figure 10-11 Snapshot Windows

A sample window snapshot

At the bottom of the Snapshots window there are icons that allow you to export, open, rename, and delete selected snapshots.

10.14 How to Calibrate the Profiler

You must calibrate the IDE before you can use the IDE to profile an application. You must run the calibration process for each JDK that you use for profiling. You do this because instrumenting the bytecode of the application imposes some overhead, and the time spent in code instrumentation needs to be "factored out" to achieve more accurate results.

You only have to calibrate the IDE once for each JDK that you use. However, you should run the calibration process again when anything changes on your local or remote configuration that could affect system performance. The following could affect system performance:

  • Any hardware upgrade

  • Any significant change or upgrade of the operating system

  • An upgrade of the Java platform used for profiling

To calibrate the IDE on your local system:

  1. Close any other programs that are running.

    The IDE runs the calibration if other applications are running, but running any CPU-intensive programs when performing the calibration might affect the accuracy of profiling results.

  2. Go to Tools > Preferences > Profiler > Manage Calibration Data and click the Manage button.

    The Manage Calibration Data window appears.

  3. Select the Java Platform to be used for profiling. Click Calibrate.

    You can click Java Platforms to open the Manage Libraries window to add a new Java platform. The Manage Calibration Data dialog box displays the date that the most recent calibration was performed.

When you click Calibrate, the IDE collects calibration data on the selected Java platform. When the calibration process is complete you can start using the IDE to profile your applications.

Do not share calibration data between various computers or systems.

10.15 How to Set Profiling Points

A profiling point is a marker in your source code which can invoke specific profiling actions. You set a profiling point in your code by using the popup menu in the Source Editor or by using the toolbar in the Profiling Points window.

You can set the following types of profiling points:

  • Reset Results

  • Stopwatch

  • Take Snapshot

  • Timed Take Snapshot

  • Triggered Take Snapshot

Note: Icons for the Timed Take Snapshot and Triggered Take Snapshot do not display in code editors. They only display in the Profiling Points window.

You can use a profiling point to reset profiling results, take a snapshot or record the timestamp or execution time of a code fragment.

Once you set a profiling point it becomes part of the project until you delete it.

To set a profiling point:

  1. Locate the class where you want to add the profiling point and open the class in the Source Editor.

  2. In the Source Editor, right-click in the gutter on the line where you want to add the profiling point.

  3. Select Add Profiling Point to open the New Profiling Point wizard.

  4. Select a profiling point type and the project.

  5. Click Next.

  6. Customize the properties of the profiling point, if necessary.

  7. Click Finish.

An icon representing the profiling point type appears in the Source Editor where you inserted the profiling point.

To enable or disable a profiling point, in the Source Editor, right-click in the left margin of the line containing the profiling point and choose <Profiling point name> > Enable or Disable.

To view active profiling points:

  1. Open the application.
  2. From the main menu, select Run > Profile.. The last profile mode session is displayed. and a Profiling Points section appears.

    Alternatively you may select Window > Profiling > Profiling Points.

  3. Use the Project or Profiling Point columns to view the defined profiling points.

10.16 Unit Testing with JUnit

JUnit is an open source regression testing framework for Java. Use JUnit to write and run tests that verify Java code.

Use JUnit wizards in JDeveloper to create test fixtures, cases, and suites. In addition to wizards for creating test components for generic projects, specialized wizards for business components projects are provided.

10.16.1 Creating a JUnit Test for a Java Project

A JUnit test application consists of the following components:

  • One or more test cases, which invoke the methods that are to be tested, and make assertions about the expected results. While test case classes generated by default have 'Test' in their names, the user can specify any valid Java name.

  • Test fixtures, which provide the state in which the tests are run. Any class can serve as a test fixture, but JDeveloper provides wizards to help you create specialized test fixture classes. While test fixture classes generated by default have 'Fixture' in their names, the user can specify any valid Java name.

  • A test suite, which invokes the test cases. Default test suite classes have 'AllTests' in their names.

  • A runner, which invokes the test suite and collates and displays the results of the tests.

10.16.2 How to Create a JUnit Custom Test Fixture

A test fixture is a set of objects, having known values, that provide data for the test cases. Any class can serve as a test fixture, but JDeveloper provides wizards to help you create custom test fixture classes and various specialized test fixture classes.

Note:

UnitTestFixture is a public class. If you create an instance of it, there will be no errors in generated code.

AppModuleAMFixture is a private class. If you create an instance of it, there will be errors in the generated code.

To create a JUnit custom test fixture class:

  1. In the Applications window, select the project.
  2. Choose File > New > From Gallery.
  3. In the Categories tree, expand General and select Unit Tests.
  4. In the Items list, double-click Test Fixture.
  5. Complete the wizard to create the test fixture class.

    The class created by the wizard will be opened for editing.

  6. Modify the file as needed.

    In particular, add code that initializes test fixture objects to the setUp() method. Add code that releases any resources they acquire to the tearDown() method.

10.16.3 How to Create a JUnit JDBC Test Fixture

A test fixture is a set of objects, having known values, that provide data for the test cases. A JDBC test fixture provides code that establishes a database connection for the test cases to use.

To create a JUnit JDBC test fixture class:

  1. In the Applications window, select the project.

  2. Choose File > New > From Gallery.

  3. In the Categories tree, expand General and select Unit Tests (JUnit).

  4. In the Items list, double-click Test Fixture.

  5. Complete the dialog to create the test fixture class.

    The class that was created will be opened for editing.

  6. Modify the file as needed. In particular, to the setUp() method add code that initializes test fixture objects, and to the tearDown() method add code that releases any resources they acquire.

10.16.4 Creating a JUnit Test Case

A test case class has one or more methods that perform tests by calling JUnit assertions. The following is a typical test case in JUnit 3.x. It passes test fixture data to the method being tested, and then compare the result with a known value to confirm that it is what is expected.

public void testCountChars()
{
      int expected = 4;
      int actual = fixture1.countChars('a');
      assertEquals(expected, actual);
}
@Test
public void testCountChars()
{
      int expected = 4;
      int actual = fixture1.countChars('a');
      Assert.assertEquals(expected, actual);
}

In the test case above, countChars() is being tested, and the result of the test is checked by assertEquals(), which is one of a variety of assertion methods defined in the JUnit Assert class. The state of the test fixture, fixture1, is established in the setUp() method, which will have been called before the test case is called, as shown below:

protected void setup() throws Exception
{
fixture1 = new StringFixture("Goin' to Kansas City, Kansas City, here I come.");
}

To create a JUnit test case class:

  1. In the Applications window, select the project or the particular class that you want to test.
  2. Choose File > New > From Gallery.
  3. In the Categories tree, expand General and select Unit Tests.
  4. In the Items list, double-click Test Case.
  5. In the Select the Class to Test page of the Create Test Case dialog, enter the class under test or click Browse.
  6. In the Class Browser dialog, locate the class you want to test or enter the beginning letters in the Match Class Name field. The Match Class list will be filtered for easier identification.

    Select the class and click OK to close the dialog. Click Next.

  7. Select the individual methods you want to test and click Next.
  8. In the Setup Test Case Class page, enter the name of the test case, the package, and the class it extends and select the list of built-in functions JUnit will create stubs for. Click Next.
  9. In the Select Test Fixtures page, select any test fixtures you want to add to the test case or click Browse.
  10. Make sure that all the test fixtures you want to add to the test case are selected in the list and click Finish.

    The class created by the wizard will be opened for editing.

You can create a test case specifically for an EJB application. For more information, see How to Test EJB Unit with JUnit.

10.16.5 How to Add a Test to a JUnit Test Case

You can add a unit test for a method to an existing JUnit test case class.

To add a test to a JUnit test case class:

  1. In the code editor, select a method for which you want to create a new unit test.
  2. From the main menu, choose Source > New Method Test.
  3. Select Add to Existing TestCase Class.
  4. From the Class Name dropdown box, or by using Browse, select the test case class that you want to add the new test to.
  5. To add the new test to the test case, click OK.

10.16.6 Creating a JUnit Test Suite

A test suite is a class that invokes test cases.

The JUnit Test Suite wizard has options to insert a main() method and a call to a TestRunner class. Within JDeveloper, this will open the JUnit TestRunner log window to display the test results. Edit the method if you wish to use a different test runner.

In the JUnit 3.x test suite shown below, the suite() method creates a TestSuite instance and adds the test cases to it. Edit this method if you wish to add or remove test cases.

public class AllTests {
    public static Test suite() {
    TestSuite suite;
    suite = new TestSuite("project1.AllTests");
    return suite;    }        

In the JUnit 4 test suite shown below, the test case classes are written with @Suite and @RunWith annotations.

@RunWith(Suite.class)
@Suite.SuiteClasses( {})
public class AllTests1 {
    public static void main(String[] args) {
    String[] args2 = { AllTests1.class.getName() };
    org.junit.runner.JUnitCore.main(args2);
    }
}

To create a JUnit test suite class:

Before you create a JUnit test case, you must have created a project that is to be tested.

  1. In the Applications window, select the project.
  2. Choose File > New > From Gallery.
  3. In the Categories tree, expand General and select Unit Tests (JUnit).
  4. In the Items list, double-click Test Suite.
  5. Complete the wizard to create the test suite class. The class created by the wizard displays for editing.
  6. Modify the file as needed. In particular:
    • In the suite() method, add the test cases.

    • In the main() method, replace the runner invocation, if desired.

10.16.7 How to Create a Business Components Test Suite

The test fixture that is created is a singleton class to reduce the number of connections. If you want to connect or disconnect for each test case, customize the test case using the JUnit 4 annotations @Before and @After.

The JUnit BC4J Test Suite wizard will generate tests for each view object in the application module. If the application module does not have exported methods, the wizard will also generate a test for the application module itself. A generated view object class has the format view_objectVOTest.java and is placed into a package with the format package.view.viewobjectVO, where package is the application module package. A generated application module test has the format application_moduleAMTest.java and is placed into a package with the format package.applicationModule. A generated test fixture class has the format applicationmoduleAMFixture.java and is placed in the same package as the application module test.

The generated all test suite class has the format AllapplicationmoduleTest.java and is placed into the package with the same name as the application module package name.

A test case XML file is also generated for each application module or view object test. The XML file contains test methods defined in the application module or view object test cases. It does not include the test methods from the base classes (if any) because there may be too many duplicates.

To create a business components test suite:

  1. In the main menu, choose File and then New.

    You will create a separate project for the business components tests.

  2. In the New Gallery, expand General, select Projects and then Java Projects, and click OK.
  3. In the Project Name page of the Create Java Project wizard, enter a name and the directory path for the test project, and click Next.
  4. In the Project Java Settings page, enter the package name, the directory of the Java source code in your project, and output directory where output class files will be placed, and click Finish.
  5. In the Applications window, double-click the application module you want to test.
  6. In the overview editor, click the Java navigation tab.
  7. In the Java page, click the Edit icon for the Java Class section.
  8. In the Select Java Options dialog, select Generate Application Module Class and click OK.
  9. In the Java page of the overview editor, click the Edit icon for the Class Interface section.
  10. In the Edit Client Interface dialog, shuttle the methods you want to test to the Selected pane, and click OK.
  11. In the Applications window, right-click the test project you have created and choose New.
  12. In the New Gallery, expand General, select Unit Tests and then Business Components Test Suite, and click OK.
  13. In the Configure Tests page of the JUnit BC4J Test Suite wizard, select values for the following and click Next:
    • Business Component Project: Select the project that has the application module you want to test.

    • Application Module: Select the application module you want to test.

    • Configuration: Choose a local or shared application module.

    • Test Base Class-Application Module Extends: You can specify different base cases. The generated test case classes will extend from that base class where all public abstract methods in the base class will have simple and default implementation method bodies.

    • Test Base Class-View Object Extends: You can specify which class the view object extends. The generated test case classes will extend from that base class where all public abstract methods in the base class will have simple and default implementation method bodies.

  14. In the Summary page, verify the selections and click Finish.

10.16.8 How to Create a Business Components Test Fixture

When you create a business components test suite, a business components test fixture is created with it. You can also create Business Components test fixtures independently.

A generated test fixture class has the format applicationmoduleAMFixture.java and put into a package with the format package.applicationModule, where package is the application module package.

To create a business components test fixture:

  1. In the main menu, choose File > New > From Gallery.

    You will create a separate project for the business components tests.

  2. In the New Gallery, expand General, select Projects > Java Project, and click OK.
  3. In the Project Name page of the Create Java Project dialog, enter a name and the directory path for the test project, and click Next.
  4. In the Project Java Settings page, enter the package name and the source and output directories, and click Finish.
  5. In the Applications window, double-click the application module you want to test.
  6. In the overview editor, click the Java navigation tab and then click the Edit icon for the Java Class section.
  7. In the Select Java Options dialog, select Generate Application Module Class, and click OK.
  8. In the Java page of the overview editor, click the Edit icon for the Class Interface section.
  9. In the Edit Client Interface dialog, shuttle the methods you want to test to the Selected pane, and click OK.
  10. In the Applications window, right-click the test project you have created and choose New.
  11. In the New Gallery, expand General, select Unit Tests and then Business Components Test Fixture, and click OK.
  12. In the Configure Tests page of the JUnit BC4J Test Fixture wizard, select values for the following and click Next:
    • Business Component Project: Select the project that has the application module you want to test.

    • Application Module: Select the application module you want to test.

    • Configuration: Choose a local or shared application module.

  13. In the Summary page, verify the test fixture class and click Finish.

10.16.9 How to Update a Test Suite with all Test Cases in the Project

You update a test suite with all test cases in a project.

To update a test suite:

  1. In a class that has a suite() method, from the context menu, choose Source > Refresh Test Suite.
  2. Ensure that all items in the list of test cases are checked.
  3. To update the test suite, click OK.

10.16.10 How to Run JUnit Test Suites

When your test suite has been successfully compiled you can run it.

To run a JUnit test suite:

  1. In the Applications window, select the test suite class.
  2. Right click it, and choose Run.

    The test executes and the test runner displays the results.