You are on page 1of 23

Analyze Memory-Related Problems in Your ABAP Programs in Less Time and with Less Effort Using the ABAP

Memory Inspector
2004 SAP Professional Journal. Reproduction prohibited. All rights reserved. 31
(complete bios appear on page 52)
As any ABAP developer is painfully aware, diagnosing a memory
problem in your application can be a tedious and time-consuming affair
due to the dynamic nature of the situation. The amount of memory
an ABAP program consumes depends on the amount of data being
processed, which is typically stored in some type of in-memory structure
(such as an internal table) that grows dynamically to accommodate the
stored data. If the amount of stored data to be loaded into memory
exceeds the size of the available storage area, the program terminates,
possibly with a runtime error such as SYSTEM_NO_ROLL or
TSV_TNEW_PAGE_ALLOC_FAILED.
Because these errors can arise for a variety of reasons, the root
cause may not be immediately obvious. For example, the runtime
error TSV_TNEW_PAGE_ALLOC_FAILED occurs when the system
cant increase the size of an internal table due to insufficient available
memory. However, this internal table might not be the reason why
memory is exhausted. What you need in this situation is a tool to help
you determine the real reason that the application has run out of memory.
In the past, this potentially laborious undertaking required you to
analyze expert-level system area displays in the ABAP Debugger
for example, the list of loaded programs, the list of loaded classes, the
list of object instances, or the ranked list of internal tables. Now you
have a better option. The ABAP Memory Inspector is available starting
with SAP NetWeaver 04 and for SAP Web Application Server (SAP
Web AS) 6.20 as of Basis Support Package 29. The ABAP Memory
Inspector provides you with an overview of dynamically allocated data
(that is, all dynamic in-memory structures) at a particular time, which
can be very helpful for diagnosing memory consumption problems, as
well as a specialized transaction for analyzing this data.
Analyze Memory-Related Problems
in Your ABAP Programs in Less
Time and with Less Effort Using the
ABAP Memory Inspector
Christian Stork and Wolf Hagen Thmmel
Wolf Hagen Thmmel,
NetWeaver Developer Tools
ABAP Group, SAP AG
Christian Stork, NetWeaver
Developer Tools ABAP
Group, SAP AG
This article originally appeared in the November/December 2004 issue of
SAP Professional Journal and appears here with the permission of the
publisher, Wellesley Information Services. For information about SAP
Professional Journal and other WIS publications, visit www.WISpubs.com.
SAP Professional J ournal November/December 2004
32 www.SAPpro.com 2004 SAP Professional J ournal. Reproduction prohibited. All rights reserved.
This article begins with an introduction to the
basics of memory management in the ABAP runtime
environment. Because this process is transparent to
application developers, you dont need to become an
expert on how it works. However, the level of detail
we provide will help you identify (and hopefully
avoid) common mistakes in your ABAP programs.
In addition, this hard-to-find information is beneficial
for improving your ABAP programs even if you
dont yet have access to the ABAP Memory Inspector.
Also, any program written in a language that supports
dynamic object creation can easily run out of memory.
Consequently, the memory management principles
discussed in this section apply to many other lan-
guages (Java, for example) as well as ABAP.
We will then draw your attention to common mis-
takes that can increase memory consumption. We will
focus on memory leaks, which manifest themselves by
your program working fine for some time and then
suddenly terminating due to a lack of memory. This
behavior occurs when a program allocates more and
more resources, but fails to release them when they
are no longer used. For programs that are running
for a long time, even a small memory leak can result
in a considerable amount of consumed, but unusable,
memory. Such errors are typically difficult to identify,
as they only emerge after some period of time.
Finally, we will demonstrate how the ABAP
Memory Inspector can help you identify memory
leaks in your programs by viewing dynamically cre-
ated objects either a list of all those that are cur-
rently residing in memory or only the largest, ranked
by size. With this knowledge, you can quickly assess
the current state of memory consumption for your
ABAP program and pinpoint the most likely source
of your problems.
Basic Principles of Memory
Management
Running out of memory can occur in any program-
ming language that supports dynamic object creation.
Consequently, the memory management principles we
discuss here apply to many other languages (Java, for
example) in addition to ABAP.
To build an application, you write programs in a
programming language, and then compile the pro-
grams into an executable format for a runtime envi-
ronment. When you start an application in a runtime
environment, the system allocates memory for the cur-
rent run. If the application terminates, the system
frees all allocated memory. Think of memory use as
being divided into two parts the memory used by
the runtime environment and the memory used by the
application. While runtime environment memory con-
sumption is beyond your control, application memory
consumption is your responsibility.
How can you influence memory consumption? To
start with, programming languages offer the ability to
define static variables in a program for handling fixed-
size data that is known at design time. For static vari-
ables, memory consumption is constant because the
size of the data is statically defined. Memory con-
sumption can only change if you change the program.
In most cases, defining static variables is insuffi-
cient, because at design time you often dont know
how much data the application needs to process.
Therefore, programming languages also offer a way to
create or expand in-memory storage structures dynam-
ically during runtime. We refer to these dynamic
structures generically as memory objects.
Dynamically creating or resizing memory objects
increases the memory consumption of a program,
however. For dynamic memory objects, memory
consumption is variable and depends on the amount
of data being processed. As memory is a limited
resource, you are responsible for releasing memory
that is no longer being used. You have two ways to
release memory:
Include a delete statement (as defined in the par-
ticular programming language in use) in your pro-
gram to explicitly destroy the memory object and
thus release the memory that it occupied.
Rely on an automatic mechanism called a garbage
Analyze Memory-Related Problems in Your ABAP Programs in Less Time and with Less Effort Using the ABAP Memory Inspector
For site licenses and volume subscriptions, call 1-781-751-8799. 33
collector, which is typically implemented in the
runtime environment of object-oriented program-
ming languages. The garbage collector automati-
cally detects and releases memory objects that are
no longer being used by an application. You dont
need to include any special statements in your
program to explicitly delete a dynamically created
memory object. Instead, your task is to delete all
references to the memory object, which allows the
garbage collector to detect the object as garbage
and release it.
If you dont explicitly release memory objects or
delete references to them, the application has a mem-
ory leak, a condition that leads to a steady increase in
memory consumption and potentially a runtime error.
Note!
ABAP is a hybrid programming language that
combines characteristics of an object-oriented
programming language and a procedural
programming language, including support for
creating and deleting memory objects.
Understanding Memory Objects in ABAP
To understand how memory leaks occur in an ABAP
program, and how the ABAP Memory Inspector can
help you in these situations, you first need to know
what types of memory objects (that is, dynamically
created in-memory objects) exist. ABAP supports
four types of memory objects:
Table body (a list of lines with the same structure)
String (a character or byte array)
Class object (an instance of a class created by the
CREATE OBJECT ABAP statement)
Anonymous data object (an instance of a data type
created by the CREATE DATA ABAP statement)
To access a memory object in a program, you use
a variable that is a reference to the memory object.
Consequently, ABAP supports four corresponding
types of references:
Table body reference (commonly called an
internal table)
String reference
Object reference
Data reference
References have either value semantics or
reference semantics. These concepts are important
to understanding memory management, so well take
a closer look at them here.
First lets examine value semantics. Lets say we
have two references, Aand B, and that Apoints to a
memory object. With value semantics, the assignment
B = Awill trigger a copy operation that creates a copy
of the memory object. After the copy operation, refer-
ence Awill still point to the original memory object,
while reference B will point to the object copy.
Modifications made via reference B will then only
affect the object copy, while the object referenced by
Awill remain unchanged. In ABAP, table body refer-
ences and string references have value semantics.
In contrast, with reference semantics the assign-
ment B = Awill point references Aand B to the same
memory object. Since there is only one memory
object involved, modifications made via reference B
will also be visible to reference A, and vice versa. In
ABAP, object references and data references have ref-
erence semantics.
As internal tables and strings can become very
large, the copy operation that occurs when there is an
assignment between references that have value seman-
tics may be quite time-consuming. On the other hand,
the copy operation is only necessary if a modification
is made via one of the references, which is not always
the case. For this reason, the ABAP runtime delays
the copy operation until a modification is actually
SAP Professional J ournal November/December 2004
34 www.SAPpro.com 2004 SAP Professional J ournal. Reproduction prohibited. All rights reserved.
made. This delay is possible because multiple table
body or string references can refer to the same table
body or string, respectively. These object types (table
bodies and strings) keep track of the number of refer-
ences that point to them, which is referred to as
reference counting. The actual copy operation
occurs when the program performs an update opera-
tion on the memory object via one of the references.
From that point forward, each reference points to its
own individual table body or string.
This behind-the-scenes behavior for references
that have value semantics is an optimization provided
by the ABAP runtime environment that is transparent
to application developers. Consequently, in common
use, a table body reference is simply called an internal
table and a string reference is called a string. But in
order to understand the memory consumption of
your programs, you must understand the technical
implementation of references with value semantics,
and be able to distinguish between the table body and
string memory objects themselves, and the references
to them.
Figure 1 illustrates the difference in behavior
between value semantics with delayed copy and refer-
ence semantics.
On the left are two table body references, itab1
and itab2, where itab1 is initial and itab2 points to a
table body. After the MOVE statement, the two table
body references itab1 and itab2 point to the same
memory object, which now has a reference count of
two. The copy operation has not yet occurred, but
as long as neither of the two references is modified,
this makes no difference. Before the MODIFY state-
ment acts on table body reference itab1, it copies the
previously shared memory object automatically. In
the end, each reference points to its own memory
object, and the reference count of both table bodies
is one, as expected for reference types that have
value semantics.
On the right are two data references, ref1 and ref2,
where ref1 is initial and ref2 points to an anonymous
data object. After the MOVE statement, ref1 and ref2
point to the same memory object, because this refer-
ence type has reference semantics. Modifications to
one reference are visible to the other.
Deleting Memory Objects
Since you can create memory objects in your pro-
grams, you must also be able to delete them. For table
references or string references, use the ABAP state-
ments CLEAR, FREE, and REFRESH.
1
Applying
these statements to a reference variable pointing to a
string or table body that is also referenced by other
reference variables (in other words, to a memory
object that is shared by multiple references) leaves the
memory object alive, decrements its reference count
by one, and sets the reference variable to the type-
specific initial value. Memory will only be freed once
the table body or string is no longer shared by other
references (or, in other words, once the reference
count is one) when the delete operation occurs. A
memory leak simply cannot occur as long as you
remember to clear all internal tables or string refer-
ences once they are no longer used.
In contrast, you cant explicitly delete class
objects or anonymous data objects. If you no longer
need a class object or an anonymous data object, clear
all references to the class object or anonymous data
object with the ABAP statements CLEAR or FREE.
The ABAP garbage collector can then delete the
object for you.
How the ABAP Garbage Collector Works
Table bodies, class objects, and anonymous data
objects can themselves contain references to other
memory objects. Consequently, you can conceivably
construct chains of memory objects in your program,
like the one shown in Figure 2. Note that the ellipses
represent memory objects, while the rectangle repre-
sents a reference.
1
The semantics of the CLEAR and FREE statements differ slightly when
applied to internal tables, which is not important in this context. For
details, refer to the online documentation for the ABAP language. The
REFRESH statement applies only to internal tables.
Analyze Memory-Related Problems in Your ABAP Programs in Less Time and with Less Effort Using the ABAP Memory Inspector
For site licenses and volume subscriptions, call 1-781-751-8799. 35
Figure 1 Comparison of Value Semantics and Reference Semantics
Value Semantics with Delayed Copy
MOVE itab2 TO itab1
1
10
20
itab1
MODIFY itab1 INDEX 3 FROM 30
1
10
30
itab2 itab1
1
10
20
1
10
20
Reference Semantics
MOVE ref2 TO ref1
ref1
ref1->* = 20
10
itab2
itab1 itab2
ref2
ref1 ref2
10
ref1 ref2
20
Figure 2 Chain of Memory Objects
Reference object1 object2 object4
object5
table body
SAP Professional J ournal November/December 2004
36 www.SAPpro.com 2004 SAP Professional J ournal. Reproduction prohibited. All rights reserved.
How do you delete such a chain? Do you need to
clear all references in the chain? No you only need
to clear the root reference! The ABAP garbage collec-
tor handles deleting all the other objects. Armed with
this knowledge, you can avoid writing complicated
and time-consuming algorithms to delete unneeded
chains of memory objects.
To further explain this concept, lets venture
briefly into the world of discrete mathematics and
graph theory. Chain isnt really the correct term for
describing a set of connected memory objects. The
correct term is graph. Since the references have a
direction (in other words, a reference points to a par-
ticular object), this graph is referred to as a directed
graph. The references are the edges, and the memory
objects together with the root set of the applications
global references are the vertices. The root set of
global references consists of global variables that are
references, local variables on the ABAP stack that are
references, and static events of classes.
Now we can see how the ABAP garbage collector
works. The garbage collector starts at the root set and
follows all references. Upon finding a class object or
an anonymous data object, the garbage collector adds
it to a list of objects known to be alive. Once the
garbage collector has followed all references, it
compares the list of known live objects and the list
of all created objects. It then deletes all class objects
and anonymous data objects that are not on the list
of known live objects. If a deleted class object or
anonymous data object contains references to any
table bodies or strings that have no other references,
the garbage collector deletes those table bodies and
strings as well.
Note!
Because table bodies and strings use reference
counting, by definition they cant exist unless a
reference points to them. Therefore, the ABAP
garbage collector doesnt track table bodies
or strings.
Figure 3 shows an example of a directed graph to
illustrate the garbage collection process. If you cleared
the references shown as dashed lines in your program,
the garbage collector would delete the white objects.
Figure 3 Directed Graph of Memory Objects
Root Set
Analyze Memory-Related Problems in Your ABAP Programs in Less Time and with Less Effort Using the ABAP Memory Inspector
For site licenses and volume subscriptions, call 1-781-751-8799. 37
The garbage collector is part of the ABAP runtime
environment, and for performance reasons it does its
work incrementally. It is triggered when the runtime
environment processes statements that may need addi-
tional memory for completion, such as statements that
create memory objects or insert rows into internal
tables. The garbage collector doesnt try to collect
all existing garbage in one step. Instead, it performs
part of the task and allows application processing to
resume until it is triggered again. Heuristics deter-
mine whether the garbage collector performs an incre-
mental collection step when triggered based on two
contradictory requirements:
Minimize the garbage collectors runtime.
Minimize the memory consumption of the
applications garbage.
As a result of the tradeoff between these require-
ments, some garbage always exists in memory.
Calculating Memory Consumption
So how do you calculate memory consumption for a
specific memory object that is embedded in a directed
graph of memory objects? Lets start with the size
of the memory object itself, which is the amount of
memory that is allocated upon creation. When the
memory object is deleted (either explicitly by the
program or implicitly by the garbage collector), this
amount of memory is released. By totaling the size
of the memory object and the size of all its children,
grandchildren, and so on, you have a value that is
called the referenced memory. Obviously, other
memory objects can also reference any child of a
memory object, and as long as at least one reference
to that child remains, it cannot be deleted. Therefore,
the amount of memory released upon deletion of a
memory object is always less than or equal to the
referenced memory of the object.
Because internal tables and string references have
value semantics, you could consider a table body or
string as part of the parent memory object. However,
this perspective only makes sense if the reference
count (that is, the number of references to the table
body or string) is one. Therefore, the bound mem-
ory of a memory object is the sum of the size of the
memory object and the bound memory of all direct
children that are table bodies or strings with a refer-
ence count of one.
2
Amemory object can only be deleted either
explicitly or implicitly if the directed graph doesnt
contain any path from the root set to the memory
object. Upon deleting the memory object, the bound
memory is the minimum amount of memory that is
released, and the referenced memory is the maximum
amount that can be released. Therefore, the amount
of memory that is actually released is somewhere
between these two values.
Memory use can vary significantly between
applications. For table bodies and strings, the runtime
environment uses a preallocation mechanism that
automatically reserves some extra storage when the
memory object is created to allow for potential
growth. Because these types of memory objects
require consecutive chunks of memory storage, this
technique avoids many allocation and deallocation
operations. Otherwise, the runtime environment
would have to allocate new storage every time the
memory object grows (such as when additional rows
are added to an internal table), copy the memory
object to the new location, and discard the memory
object in the previous location.
Due to this preallocation mechanism, both table
bodies and strings also have allocated memory and
used memory values as memory sizes. Allocated
memory is the amount of memory that is set aside for
the memory object. Used memory is the current size
of the memory object used by the application. When a
new memory object is created, the allocated memory
consists of the used memory plus additional storage to
accommodate growth. For class objects and anony-
mous data objects, used memory and allocated mem-
ory are the same. Because their size is fixed, they
dont require additional space to accommodate growth.
2
You might expect this definition of bound memory i.e., the amount
of memory that is freed upon deletion to also apply to class objects
and anonymous data objects. While not currently supported, this
enhancement is planned for an upcoming release of SAP NetWeaver.
SAP Professional J ournal November/December 2004
38 www.SAPpro.com 2004 SAP Professional J ournal. Reproduction prohibited. All rights reserved.
These two value pairs (bound memory and refer-
enced memory, plus used memory and allocated mem-
ory) are orthogonal. Therefore, memory objects
actually have four size values:
Bound, used memory
Bound, allocated memory
Referenced, used memory
Referenced, allocated memory
Computing the total size of a memory object is a
recursive process. For our purposes, we can under-
stand the concept by examining how to compute the
size of a particular memory object that references
other memory objects. Figure 4 shows the formulas
for computing the various size values for the circled
memory objects obj1, obj3, and obj4. The memory
object labeled obj2 is either a class object or an
anonymous data object, str1 and str2 are either string
objects or table bodies, and obj5 is any kind of mem-
ory object that can contain references to other memory
objects (i.e., a table body, a class object, or an anony-
mous data object). The referenced size is computed as
the sum of the memory object size and the size of all
referenced objects. For the bound size, we can only
add the size of referenced objects that are exclusively
referenced by the memory object in question.
When computing the bound size of obj1, we do
not know whether child obj2 is referenced by another
memory object, because obj2 does not support refer-
ence counting (this is indicated by the question mark
and dotted lines). So we cannot include the size of
obj2 when computing the bound size of obj1. In con-
trast, for obj3 we can add the size of str1 when calcu-
lating the bound size (as indicated in the table in
Figure 4), as the reference count of str1 is one, and we
are therefore certain that str1 is exclusively referenced
by obj3. On the other hand, the reference count of
str2 is known to be two (it is referenced by obj4 and
obj5), so we do not add the size of str2 when comput-
ing the bound size of obj4.
It is important to understand the difference
between the definition of the bound size of memory
objects having references to other class objects or
anonymous data objects, and the bound size of mem-
ory objects having only references to table bodies or
strings. In the first case, we simply cannot determine
whether the child object is referenced exclusively by
Figure 4 Computing the Size of Memory Objects
Bound,
allocated
Bound,
used
Referenced,
allocated
Referenced,
used
s(obj1,a) s(obj1,u) s(obj1,a)+
s(obj2,a)
s(obj1,u)+
s(obj2,u)
s(obj3,a)+
s(str1,a)
s(obj3,u)+
s(str1,u)
s(obj3,a)+
s(str1,a)
s(obj3,u)+
s(str1,u)
s(obj4,a) s(obj4,u) s(obj4,a)+
s(str2,a)
s(obj4,u)+
s(str2,u)
obj2 obj1
?
s : {Memory Object} x {a(llocated),u(sed)} Memory Size in Bytes
Legend:
Memory
Object
str2 obj4
obj5
str1 obj3
Class object or
anonymous data object
String or
table body
Analyze Memory-Related Problems in Your ABAP Programs in Less Time and with Less Effort Using the ABAP Memory Inspector
For site licenses and volume subscriptions, call 1-781-751-8799. 39
the parent object, so we never include the child size
when computing the bound size of the parent object.
In the latter case, we can rely on the reference count
of the child objects when computing the bound size of
the parent object.
In the table, s is a function that calculates the allo-
cated or used memory size (indicated by the parameter
a for allocated or u for used, respectively) of a mem-
ory object in bytes. As a preallocation mechanism is
only used for table bodies and strings, the allocated
and used memory size can only differ for table bodies
and strings. For class objects or anonymous data
objects, these two values are identical.
Investigating Memory Leakage
in ABAP Programs
Before SAP Web AS 6.10, memory leakage was a less
serious problem for ABAP applications. ABAP pro-
vided limited support for handling dynamic data
(internal tables only), and transactions were mostly
short-lived. At the end of a transaction, the entire
internal session was discarded and all resources
released. As a result, memory leaks were rarely a
problem.
However, the programming model has undergone
major changes. The ABAP Objects language supports
several mechanisms for handling dynamic data (inter-
nal tables, strings, class objects, and anonymous data
objects). In addition, new types of long-lived transac-
tions remain open for an entire business day, or even
longer. In such an environment, we can no longer
afford to ignore memory leakage.
Common Sources of Memory Leakage or Waste
In our experience, a few common programming pat-
terns can lead to suboptimal memory use. Whether
the results lead to severe problems (possibly up to
application termination) or not depends largely on fac-
tors such as the lifetime of the internal session, the
number of parallel users, and the amount of memory
available on the application server. To leak-proof
your programs, watch for these often-overlooked
sources of problems:
Unreleased references: Remember that dynami-
cally created memory objects remain alive as
long as they are referenced. Acommon source
of unreleased references is a directory of dynami-
cally created memory objects in a program (for
example, storing references to these objects in
an internal table). Dont forget to remove refer-
ences from the directory once the objects are
no longer needed. Otherwise, the references
stored in the internal table keep all correspon-
ding objects alive.
3
Low used-to-allocated memory ratio: You can
create ABAP internal tables with an arbitrary size
by using the INITIAL SIZE parameter. Using this
parameter carelessly can lead to wasted memory
if the application cant ever fill the allocated size.
Also remember that the ABAP runtime environ-
ment automatically increases the allocated mem-
ory for an internal table as needed when rows are
added, but never decreases the allocated memory,
even if all the rows have been deleted. For this
reason, internal tables in the root set that are only
used during the early stages of an application are a
potential source of wasted memory. The system
cant reuse the allocated storage until the table
bodies are deleted.
When an application experiences memory prob-
lems, one or both of these conditions might represent
the underlying problem. Begin analyzing the situation
by asking yourself the following questions:

Why is the memory consumption of the


application increasing?
Why is the memory consumption of the
application so high?

3
When implementing a cache, you may want to store object references
for subsequent use to increase application performance. For this
purpose, use weak references that cant keep an object alive.
For details, refer to the online documentation for the
CL_ABAP_WEAK_REFERENCE class.
SAP Professional J ournal November/December 2004
40 www.SAPpro.com 2004 SAP Professional J ournal. Reproduction prohibited. All rights reserved.
In the past, getting the answers to these questions
was unlikely unless you had expert knowledge of the
ABAP runtime environment (which for most of us is
generally not the case). Now you have the ABAP
Memory Inspector for obtaining useful clues signifi-
cantly faster and easier.
How the ABAP Memory Inspector Can Help
The ABAP Memory Inspector simplifies the process
of getting the information you need in order to diag-
nose memory consumption problems. To answer the
questions we just posed why memory consumption
is increasing and why it is so high you need two
different techniques.
To analyze the first problem (increasing memory
consumption), you need separate lists of all memory
objects that are alive at two different points in time.
By comparing these lists, you can easily identify any
new memory objects that might be increasing the
memory consumption of your program. In the next
section, we discuss how to perform this task in just a
few steps by creating and comparing memory snap-
shots in the ABAP Memory Inspector.
For analyzing the second problem (high memory
consumption), you need a list of the top memory
consumers. You can quickly generate such a list
i.e., a ranked list in the ABAP Memory Inspec-
tor, as shown in Figure 5. The columns show the
name of the program in which the memory object
was created (Label), the memory object type (Type),
the number of instances or rows (Additional info), and
the various memory sizes. The list is sorted in
Figure 5 Ranked List of Memory Objects in the ABAP Memory Inspector
Analyze Memory-Related Problems in Your ABAP Programs in Less Time and with Less Effort Using the ABAP Memory Inspector
For site licenses and volume subscriptions, call 1-781-751-8799. 41
descending order by size (Bound, Allocated).
Coincidentally, the largest memory objects in Figure 5
are internal tables.
From the example in Figure 5, you might conclude
that all of the top memory consumers of the program
are table bodies (internal tables). But it is also possi-
ble that a huge number of rather small memory objects
are consuming all the memory. This situation can
only occur with class objects and anonymous data
objects. As you create these objects dynamically
with the ABAP statements CREATE OBJECT and
CREATE DATA, respectively, the number of these
memory objects is not limited by the statically defined
references. Therefore, you also need to determine the
aggregate size of class objects and anonymous data
objects that are of the same type. Again, the ABAP
Memory Inspector simplifies this task, as shown in
Figure 6. While similar to the list in Figure 5,
Figure 6 instead shows an aggregate entry for all
instances of a class (here, LCL_LOCAL_CLASS2).
As you can see in the Additional info and Bound,
Allocated columns, approximately 9,000 instances
(objects) of the LCL_LOCAL_CLASS2 class collec-
tively consume approximately 37,054,896 bytes of
memory, or approximately 4,000 bytes per instance.
Because this value is rather small, none of the individ-
ual objects appear in the top consumer list. Yet, as
this example shows, we could have an undesirably
large number of instances for a single class. Creating
subsets of memory objects of the same type and evalu-
ating the aggregate size of the subset can be extremely
beneficial when investigating memory problems.
Figure 6 shows an example of memory objects
grouped in subsets based on the Type property.
Figure 6 Ranked List of Memory Objects, Aggregated by Type
SAP Professional J ournal November/December 2004
42 www.SAPpro.com 2004 SAP Professional J ournal. Reproduction prohibited. All rights reserved.
These examples are useful for analyzing the size
of individual memory objects individually and collec-
tively. Before delving into how to use the ABAP
Memory Inspector to generate these lists, lets revisit
the principles of graph theory in order to understand
another useful property for grouping and analyzing
subsets of memory objects strongly connected
components (SCCs) of a directed graph.
What Are Strongly Connected Components?
As we explained earlier, the combination of memory
objects and the root set of global references defines a
directed graph. Graph theory as a part of computer
science
4
defines several properties of graphs, one of
which is the strongly connected components (SCCs)
of a directed graph.
To define an SCC, you must first understand
paths in a directed graph. Suppose you have two
vertices A and B of a directed graph, as shown
in Figure 7. A path from A to B consists of edges
that construct a route for you to walk from A to B in
the direction defined by the edges. The short dashed
line edges in Figure 7 show the path from A to B,
while the long dashed line edges show the path back
from B to A.
Aconnected component of a directed graph
(lets call it P) is part of the graph with the property
that for all vertices Aand B of part P that have a path
from Ato B, a path also exists from B back to A. In
Figure 8, the white objects form a connected compo-
nent, and the paths are displayed as dashed lines.
Aconnected component P is considered a
strongly connected component if no other connected
component contains part P (lets call this SCC Q).
Being an SCC is what is referred to as a maximum
property, which means that two SCCs must be either
identical or disjointed. The three dashed line circles in
Figure 9 show the SCCs in this graph.
Root Set
A
B
Figure 7 Paths in a Directed Graph
4
For more information about graph theory, a useful source is
http://people.freenet.de/Emden-Weinert/graphs.html. Note
that the URL is case-sensitive.
Analyze Memory-Related Problems in Your ABAP Programs in Less Time and with Less Effort Using the ABAP Memory Inspector
For site licenses and volume subscriptions, call 1-781-751-8799. 43
Figure 8 Connected Component in a Directed Graph
Root Set
Root Set
Figure 9 Strongly Connected Components in a Directed Graph
SAP Professional J ournal November/December 2004
44 www.SAPpro.com 2004 SAP Professional J ournal. Reproduction prohibited. All rights reserved.
So, why are we explaining this aspect of graph
theory, and why should you care about SCCs? Due
to its properties, the ABAP garbage collector can
delete an SCC if and only if all references that point
to it are cleared. As you can see, SCCs present yet
another opportunity for potential memory consump-
tion problems.
In terms of memory consumption, think of
SCCs as larger entities that can only be deleted as a
whole. They arent undesirable, and, in fact, you
often cant avoid them because just using some data
structures (such as a double-linked list) creates an
SCC. So dont believe or expect that an application
shouldnt create SCCs. Simply keep in mind that you
need to clear all references to an SCC in order to get
rid of it.
Using the ABAP Memory
Inspector
Analyzing the memory consumption of an application
typically consists of two types of scenarios:
Youre interested in the current memory consump-
tion of a running program in order to check if it is
unexpectedly high.
You want to compare the memory consumption
of a program at different times in order to find
out if it increases in an undesirable way and to
identify which memory objects contribute to
the increase.
The ABAP Memory Inspector is designed to sup-
port both scenarios:
For analyzing the current memory consumption
of a running program, you use ABAP Memory
Inspector functionality that is embedded in the
ABAP Debugger.
For comparing memory consumption at different
times, you create memory snapshots that con-
tain comprehensive information on the current
state of the ABAP runtime memory. You then
later compare these snapshots using the
S_MEMORY_INSPECTOR transaction.
We will now show you how to perform each of
these tasks.
Analyzing Memory Consumption of a
Running Program
To generate information on the current state of mem-
ory consumption for a session, select Goto !Status
Figure 10 Memory Use Displayed in the
ABAP Debugger
Tip
The latter scenario (comparing the memory
consumption of a program at different times) is
probably more efficient for identifying memory
leaks in your code; memory leaks often manifest
themselves in the increasing size of certain objects
in memory, but not necessarily as large objects.
Analyze Memory-Related Problems in Your ABAP Programs in Less Time and with Less Effort Using the ABAP Memory Inspector
For site licenses and volume subscriptions, call 1-781-751-8799. 45
Display !Memory Use from the ABAP Debugger
menu bar. Figure 10 shows an example of the result-
ing display.
You can choose from three tabs on this display:
The Memory Use - Total tab shows a summary of
the total memory use for the application. Only
the first two values Allocated Memory and
Memory Used are of interest to application
developers. Allocated Memory is the amount
of memory that is currently reserved for the inter-
nal session by the memory management layer.
Memory Used is the part of this reserved amount
that is actually consumed by the application and
the underlying runtime environment. The Special
Memory Areas section in the lower part of the
screen contains expert-level information that isnt
relevant for our purposes.
The Memory Use - Ranked List tab lists all mem-
ory objects sorted by size in descending order.
Every object has a corresponding label and type
(such as internal table or class object). Use this
list to identify the top memory consumers in your
application and evaluate whether their sizes match
your expectations. Figures 5 and 6 show exam-
ples of a ranked list. They differ only in the cho-
sen aggregation, which you control using the
Change Settings button ( ) located above the list
area on the screen (see the sidebar on the next
page for more on the available function buttons).
The Memory Use - SCC tab provides a ranked list
of all current SCCs. The ranking is based on the
aggregate size of all contained memory objects of
each SCC. Figure 11 shows an example in which
433 memory objects (as indicated in the No. of
Nodes column) form a single SCC.
Figure 11 Ranked List of Strongly Connected Components
SAP Professional J ournal November/December 2004
46 www.SAPpro.com 2004 SAP Professional J ournal. Reproduction prohibited. All rights reserved.
Using the Function Buttons in the Memory Displays
Several function buttons located just above the list area on the ABAP Debugger Memory Use - Ranked
List and Memory Use - SCC displays offer additional content and format control. The following table
provides an overview of the buttons and their functions (note that not all function buttons are available
on both displays).
Note that if you choose type aggregation in the Change Settings pop-up, the list no longer displays details
for individual class objects and anonymous data objects. Instead, the list shows the total of their memory
sizes. This aggregation helps you identify memory leaks where a large number of small memory objects
exist, which can add up to a considerable size. Each memory object alone may easily be small enough to
never appear in the list of top memory consumers.
Button Purpose
Change Settings This button is available on both the Memory Use - Ranked List and Memory
Use - SCC displays. Clicking on the Change Settings button launches a pop-up
where you select the type of objects to display, the sorting and type aggregation
criteria, the display refresh strategy (either manually via the Refresh button or
automatically at every debug step), and the number of entries to display in the list.
Find References This button is available on both the Memory Use - Ranked List and Memory Use -
SCC displays. After selecting a row in the list, clicking on the Find References
button displays a pop-up with all references that point to the selected memory
object or SCC.
Node List This button is available on both the Memory Use - Ranked List and Memory Use -
SCC displays:
In the Memory Use - Ranked List display, clicking on the Node List button
shows a list of all memory objects of the selected type or class in the ranked
list. This button appears on this display only if type aggregation is active.
In the Memory Use - SCC display, clicking on the Node List button shows a
list of all members of the selected SCC.
Save as Local File This button is available on only the Memory Use - Ranked List display. Clicking
on the Save as Local File button saves the list as a Microsoft Excel (.XLS) file on
your local computer.
Update Ranked
List
This button is available on both the Memory Use - Ranked List and the Memory
Use - SCC displays. Clicking on the Update Ranked List button re-computes the
memory sizes and updates the ranked list. This button appears only if you choose
to refresh the display manually in the Change Settings pop-up.
Analyze Memory-Related Problems in Your ABAP Programs in Less Time and with Less Effort Using the ABAP Memory Inspector
For site licenses and volume subscriptions, call 1-781-751-8799. 47
Tip
Remember that objects inside an SCC keep each
other alive until all outside references that point
to SCC members are deleted. When looking for
memory objects that may no longer be needed
but are being unnecessarily kept alive by your
application, dont overlook SCCs. They represent
larger entities that can only be deleted as a whole.
The Memory Use - Ranked List and Memory
Use - SCC displays only show memory objects that
are considered to be alive, meaning that they are still
in use by the application and would not be deleted by
the ABAP garbage collector if it were running. To
minimize the impact on the runtime behavior, display-
ing these lists in the debugger doesnt trigger garbage
collection.
Creating Memory Snapshots for
Later Analysis
In order to analyze memory consumption outside of
the ABAP Debugger, you need a way to store memory
details for the current state. For this purpose, you use
the ABAP Memory Inspector to create a memory
snapshot, which is written to a file on the current
server. It contains administrative information about
all objects currently in memory, but not an image of
the runtime memory itself.
There are several ways to create a memory
snapshot:
When debugging an application, select
Development !Memory Analysis !Create
Memory Snapshot from the ABAP Debugger
menu bar. Acompletion message indicates when
the file is ready.
Enter the command /hmusa in the command field
on any SAPGUI screen you dont need to be in
the debugger. When the file is ready, you will see
the same completion message shown for the pre-
vious option.
Call the
WRITE_MEMORY_CONSUMPTION_FILE
method of the CL_ABAP_MEMORY_UTILITIES
class in your code. Use this option carefully to
avoid running out of disk space.
When you are analyzing memory consumption
problems, always start with one of the first two inter-
active options. The third option, which requires you
to change your code, is more appropriate for special
cases such as application startup or other stages of
your application where you may not have easy inter-
active access.
Memory snapshot file names follow the naming
convention abDbgMemory_XX_YYYY, where XX is
the number of the current work process and YYYY is
a counter. You can change the prefix abDbgMemory
via the abap/memory_inspector_file profile parameter.
The file name, which is created automatically, is
unique as long as the work process is not restarted.
All snapshots are written to the directory that is speci-
fied by the DIR_MEMORY_INSPECTOR profile
parameter. The S_MEMORY_INSPECTOR transac-
tion, which is a specialized transaction for analyzing
memory snapshots (more on this in a moment), only
displays memory snapshot files that are located in
DIR_MEMORY_INSPECTOR and have the prefix
defined by the abap/memory_inspector_file profile
parameter.
The size of a memory snapshot varies based on
the number of objects in memory and the number
of references to those objects, rather than the actual
amount of physical memory used in total. Keep in
mind that creating a memory snapshot implicitly trig-
gers the ABAP garbage collector. Consequently, snap-
shots only store live memory objects. In rare cases,
creating a memory snapshot might actually delay a
resource-related runtime error because of the forced
garbage collection. In contrast, displaying the lists
of top memory-consuming objects in the debugger
doesnt implicitly trigger garbage collection.
SAP Professional J ournal November/December 2004
48 www.SAPpro.com 2004 SAP Professional J ournal. Reproduction prohibited. All rights reserved.
Analyzing and Comparing Memory
Snapshots
The ABAP Memory Inspector provides a dedicated
transaction for displaying the content of stored mem-
ory snapshots. You start this transaction either
directly via transaction S_MEMORY_INSPECTOR, or
in the ABAP Debugger by selecting Development !
Memory Analysis !Compare Memory Snapshots
from the menu bar.
When you start this transaction in the debugger, it
is opened in a new window. The main screen consists
of two parts (see Figure 12). The upper part shows a
list of all memory snapshots located on this applica-
tion server. You can open or delete any of these snap-
shots, as well as upload or download them to your
local computer. This feature is especially useful for
archiving snapshots, as the transaction automatically
deletes snapshots that are older than four weeks.
Double-click on an entry in the list to open a snap-
shot and display its contents in the lower part of the
screen. You can have up to two snapshots open at one
time. Opening a third snapshot automatically closes
one of the others based on the difference in creation
time. The first opened snapshot is referred to as (t_0);
the second as (t_1). To select an open snapshot for
display, use the (t_0) and (t_1) buttons in the applica-
tion toolbar at the top of the screen, or use the
Memory Snapshot dropdown list located above the
display tree in the lower part of the screen.
Several views, accessible via the View dropdown
list above the display tree, enable you to display a
snapshot in different ways:
Figure 12 The ABAP Memory Inspector Transaction for Analyzing Memory Snapshots
Analyze Memory-Related Problems in Your ABAP Programs in Less Time and with Less Effort Using the ABAP Memory Inspector
For site licenses and volume subscriptions, call 1-781-751-8799. 49
Overview (the default view) shows the objects
in memory, separated by type (classes, table
bodies, etc.).
Ranked List, Ranking List by Type, and Object
Cycles (SCC) are similar to the lists you generate
in the debugger.
System Memory shows information on the mem-
ory consumed by the runtime environment, which
is less interesting for application developers,
because you have no direct control over this
aspect of memory use.
By default, objects are sorted in descending order
by the values in the first four columns, which are con-
sidered the most important for ranking. Their contents
may vary between views and memory object types.
To change the sort order, select one or more columns
and use the sorting buttons ( ) in the display
tree toolbar.
As shown in Figure 13, you can compare two
open snapshots that were created during the same
internal mode of a session (that is, if you didnt restart
the transaction between creating the two snapshots).
To start the comparison, select (t_1 - t_0) either in the
Figure 13 Comparing Memory Snapshots
SAP Professional J ournal November/December 2004
50 www.SAPpro.com 2004 SAP Professional J ournal. Reproduction prohibited. All rights reserved.
application toolbar or in the Memory Snapshot drop-
down list above the display tree. While similar to the
display of a single snapshot (Figure 12), the display
comparing two snapshots (Figure 13) has the follow-
ing differences:
Memory objects appear if:
- They exist in the second snapshot, but not in
the first (in other words, if they were newly
created).
- They exist in the first snapshot, but not in
the second (in other words, if they have
disappeared).
- One of their memory size values, such as allo-
cated or used size, has changed (for example,
if a table has grown).
New memory objects are marked with a plus sign
(+) in front of the object name.
Deleted objects are marked with a minus sign (-)
in front of the object name.
Looking at the display in Figure 13 from the top
down, left to right, you can learn the following infor-
mation about this example application and its memory
consumption:
One new program was loaded between the t_0 and
t_1 snapshots. In the Number of Programs section
in the Value 1 column, the current number of pro-
grams loaded in the t_1 snapshot is 38, and (+1)
signifies that this number has increased by one
since the t_0 snapshot.
The number of objects in memory has increased
by four since the t_0 snapshot. In the Number of
Instances section in the Value 3 column, the cur-
rent number of objects in the t_1 snapshot is
8,928, and (+4) indicates the change between the
t_0 and t_1 snapshots.
The number of tables in memory is 38, which
has increased by one since t_0. Following the
same conventions for interpreting the data, see
the Number of Tables section in the Value 4
column.
The new tables and objects belong to the
ZDEMOMI program, which we deduce from
the entries in the Programs branch of the display
tree. The changes that we just observed for the
number of objects (+4) and the number of tables
(+1) also appear in the row for the ZDEMOMI
program.
The new objects are instances of
LCL_LOCAL_CLASS, as this class appears in
the Classes (ABAP Objects) branch of the
display tree. The Number of Instances section
for this class shows a difference of four (+4).
In addition, 4,240 bytes of memory were added
to accommodate the new objects, resulting in
a total memory consumption of 5,300 bytes.
See the Bound (Allocated) and Bound (Used)
sections in the Value 2 and Value 3 columns,
respectively.
The ITAB30 table has increased by two lines, as
you can see in the Table Bodies branch of the dis-
play tree. Its the only table that has memory size
changes, as indicated by the plus signs (+) next
to the values in the row for ITAB30. No new
memory was needed, as a total of 16 lines are
already allocated.
Anew ITAB28 table was created, which has a
plus sign (+) before its name in the Table Bodies
branch of the display tree. It contains two lines,
which you can determine from the dimension
specification in the name ([2x8]) and the Lines
(Used) value in the Value 2 column. The Lines
(Allocated) section in the Value 1 column shows
that 16 lines are allocated for this table. These
extra lines are allocated to allow for future
growth.
Although four tables were deleted between the t_0
and t_1 snapshots, new tables with similar names
were created. Look at the tables with %_ prefixes
in their names. The number of allocated lines in
Analyze Memory-Related Problems in Your ABAP Programs in Less Time and with Less Effort Using the ABAP Memory Inspector
For site licenses and volume subscriptions, call 1-781-751-8799. 51
the deleted and created tables is the same, result-
ing in no impact on memory consumption. You
can ignore these tables when searching for mem-
ory leaks, as they introduce no net change in
memory consumption. Although not represented
in this example, this premise is also valid for
all other types of memory objects. For all new
objects, check whether an object of the same
type has disappeared.
Obviously these numbers only tell you something
valuable when you understand the application you
are investigating. Every application and memory
problem is unique, requiring a different approach
and resulting in a different conclusion. In practice,
you first have to examine the data you get from the
ABAP Memory Inspector. Then you must formulate
a series of probing questions that will enable you to
evaluate what the data tells you in the context of your
application, and the characteristics of the problem.
For example, did you expect this table or object to be
this large? Did you expect this table to be growing at
this rate? Did you expect to have so many instances
of this class? Only at this point can you begin to
properly diagnose the problem.
From this example, we have learned that analyz-
ing a memory snapshot gives you the opportunity to
scrutinize the types of memory objects that an applica-
tion creates and how much storage they consume.
This information is incredibly valuable when you are
experiencing memory problems. Most of the time,
you still have a lot of hard work remaining in order to
identify the specific errors in the code that produce
undesirably high memory consumption. But examin-
ing the information provided by the ABAP Memory
Inspector offers a baseline for establishing and vali-
dating your assumptions.
Analyzing Memory Snapshots of a
Running Program
When you start the ABAP Memory Inspector from the
ABAP Debugger, you have the option to automatically
open the last two snapshots that were created during
the debugging session (if any). This feature allows
you to use the ABAP Debugger (which you must keep
open) to inspect the current state of these memory
objects. In this case, the ABAP Memory Inspector
assumes that the memory objects in the memory
snapshot are still alive.
For almost any memory object shown in a
single snapshot or snapshot comparison display,
right-click on the corresponding row and select
the Display in Debugger option from the context
menu. Press ENTER in the debugger window to
display the selected memory object (if it still exists).
This technique allows you to obtain additional
information about a memory object, such as its
current value.
Conclusion
When your ABAP application terminates after some
time because memory is exhausted, one possible rea-
son is that some part of some program is consuming
memory steadily, but usually avoidably. This situa-
tion, called a memory leak, is a result of errors in the
code most often failing to return unused resources
to the runtime environment.
Identifying these types of errors requires the
ability to identify dynamically created memory
objects that increase in size over time or are created
in possibly undesirably large quantities. As the
administration of dynamic memory objects is hidden
in the ABAP runtime environment, you have almost
no way to perform this type of analysis without a ded-
icated tool.
SAP now offers the ABAP Memory Inspector,
which is specifically designed to assist you with the
difficult task of identifying memory leaks or other
memory-related problems in your code. It provides
memory consumption displays embedded in the
ABAP Debugger, the ability to create and save
memory snapshots that show the current state of
memory consumption, and a specialized transaction
SAP Professional J ournal November/December 2004
52 www.SAPpro.com 2004 SAP Professional J ournal. Reproduction prohibited. All rights reserved.
for analyzing these snapshots. As different applica-
tions have different problems, remember the general
rule you must always adopt a case-by-case
approach to analyzing the specifics of the situation.
But with the introduction of the ABAP Memory
Inspector, at least you now have a tool to help you
with the task at hand.
Wolf Hagen Thmmel studied physics and received
his doctorate at the University of Karlsruhe,
Germany. After a year of postdoctoral research
work in the field of experimental particle physics,
he joined SAP in 2001 as a member of the
NetWeaver Developer Tools ABAP Group. Wolf
Hagen works on tools for the ABAP language. He
can be reached at wolf.hagen.thuemmel@sap.com.
Christian Stork studied mathematics and computer
science at the Westflische Wilhelms-University of
Mnster, Germany. He joined SAP in 1995 and
worked for two years as a trainer, then returned to
the Westflische Wilhelms-University of Mnster
for his doctorate, specializing in algebraic
geometry. In 2000, Christian rejoined SAP and
became a member of the NetWeaver Developer
Tools ABAP Group, where he works as a
kernel developer. He is responsible for the
implementation and maintenance of the Object
Services, and is currently working on Simple
Transformations, a new Serialization and
Deserialization language. He can be reached
at christian.stork@sap.com.
About SAP Professional Journal
Elevate your mastery of SAP technology with in-depth tutorials and expert guidance in SAP Professional Journal.
Top independent consultants, experienced SAP customers and the technical gurus who write the code for SAP contribute
proven best practices and their favorites tips and techniques for developers, administrators and specialists in SAP
technology. Articles cover everything from ABAP to Java programming, from performance optimization to integration.
Each issue features step-by-step instruction on the SAP projects that top your to-do list right now. You can
immediately put to use practical advice that can't be found anywhere else.
Learn Directly From the Experts
All SAP Professional Journal authors are among the best and brightest minds in the
SAP community. The unique articles they write are training courses unto themselves.
Articles for developers often feature code samples and step-by-step development
techniques, while articles for administrators feature detailed screenshots and in-depth
guidance to enhance performance. Typical articles span 20-30 pages, and overall
coverage blends operational and theoretical background with day-to-day implications of
how and why SAP technology operates as it does, and how best to incorporate that
technology into your own IT environment. In addition we provide a complete download
library of all source and sample code featured in our articles.
Published bimonthly, every issue features highly-specific articles, each focused on
a narrow technical area or particular SAP offering. Every author is uniquely qualified to
take advanced, complex concepts and present them in an easy-to-understand format, at a
level of technical detail available nowhere else, to help advance your understanding of SAP technology.
Invest in Your Team
Keeping up with advances in SAP technology is a constant endeavor that is critical to your success, as well as to
achieving your enterprise's key business goals. Now your whole team can do so with access to every single article ever
published in SAP Professional Journal through our electronic license program. This program is the most affordable way to
access the SAP Professional Journal online archive your whole team gets one-click access to new articles, plus the
ability to search instantly through more than 3,500 pages of accumulated solutions, for a fraction of the cost of multiple
subscriptions.
Your team is your strongest asset, and giving them access to SAP Professional Journal is the best investment you
can make in them -- guaranteeing your organizations SAP knowledge and skills stay on the cutting edge. To learn more
about our Electronic License Program call 781-751-8799 or send a message to licenses@sappro.com.
Subscribe Risk-Free
SAP Professional Journal is backed by a 100% money-back guarantee. If at any point, for any reason, you are not
completely satisfied, we will refund your subscription payment IN FULL. Don't wait any longer to benefit from the most
respected technical journal for SAP expertise. This is the most in-depth publication written specifically for SAP
professionals like you. Subscribe to SAP Professional Journal today at www.SAPpro.com or call us at 781-751-8799.
SAP Professional Journal 990 Washington Street, Ste. 308 Dedham MA 02026, USA
www.SAPpro.com
the leading technical journal for
SAP administrators, architects,
consultants, and developers

You might also like