This chapter includes the following sections:
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.
You may simultaneously start a JDeveloper application and the profiling of that application by following these steps:
You may profile a JDeveloper project that is already running by following these steps:
You may profile an application that is not started from within the JDeveloper IDE by following these steps:
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
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
The objects mode provides a list of classes allocated to a project including live instances and bytes allocation. By clicking the 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
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
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
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.
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
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.
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.
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:
Open the source file containing the code where you want to place the profiling point.
Right-click in the line of code where you want to place the profiling point and select Add Profiling Point.
In the Profiling Point Type list, select one of the following snapshot options and click Next:
Take Snapshot
Timed Take Snapshot
Triggered Take Snapshot
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:
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
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.
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.
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.
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
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'))
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[].
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:
While the profiling session is in progress. See Taking Snapshots During a Profiling Session
At the end of the profiling session. See 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
Click Yes to save the snapshot.
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
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.
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
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
At the bottom of the Snapshots window there are icons that allow you to export, open, rename, and delete selected snapshots.
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:
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.
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:
Locate the class where you want to add the profiling point and open the class in the Source Editor.
In the Source Editor, right-click in the gutter on the line where you want to add the profiling point.
Select Add Profiling Point to open the New Profiling Point wizard.
Select a profiling point type and the project.
Click Next.
Customize the properties of the profiling point, if necessary.
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:
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.
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.
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.
AppModuleAMFixtur
e 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:
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:
In the Applications window, select the project.
Choose File > New > From Gallery.
In the Categories tree, expand General and select Unit Tests (JUnit).
In the Items list, double-click Test Fixture.
Complete the dialog to create the test fixture class.
The class that was created will be opened for editing.
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.
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:
You can create a test case specifically for an EJB application. For more information, see How to Test EJB Unit with JUnit.
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:
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.
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:
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:
You update a test suite with all test cases in a project.
To update a test suite:
suite()
method, from the context menu, choose Source > Refresh Test Suite.