It is necessary to know how many resources are allocated in order to know if the leak has been plugged or not. Fortunately, SWT provides a mechanism to do this via the Display
and the DeviceData
classes. Normally, this is done by a separate plug-in, but in this example ClockView
will be modified to show this behavior.
ClockView
class' createPartControl()
method, add a call to obtain the number of allocated Objects
, via DeviceData
of the Display
class:public void createPartControl(Composite parent) { Object[] oo=parent.getDisplay().getDeviceData().objects;
objects
counting how many are instances of Color
:int c = 0; for (int i = 0; i < oo.length; i++) if (oo[i] instanceof Color) c++;
System.err.println("There are " + c + " Color instances");
There are 0 Color instances There are 0 Color instances There are 0 Color instances
For efficiency, SWT doesn't log all the allocated resources all the time. Instead, it's an option which is enabled at startup through an options
file, which is a text properties file with name=value
pairs. This can be passed to an Eclipse instance at launch via the -debug
flag.
Fortunately, it is easy to set within Eclipse from the launch configuration's tracing tab.
org.eclipse.ui
plugin. Select both the debug
(at the top) and the trace/graphics
options:There are 87 Color instances There are 92 Color instances There are 95 Color instances There are 98 Color instances
Clearly, something is leaking three Color
instances each time the Clock View is opened. Not surprisingly, three instances of the Color
object are allocated in the three instances of ClockWidget
. This suggests that there is a resource leak in ClockView
or ClockWidget
.
When SWT is running in trace mode, it will keep a list of previously allocated resources in a global list, which is accessible through the DeviceData
object. When the resource is disposed, it will be removed from the allocated list. This allows the monitoring of the state of resources at play in the Eclipse workbench and discover leaks, typically through repeated actions and noting an increase each time in the resource count.
Other object types are also stored in this list (for example, Fonts
and Images
) so it's important to filter by type when looking for a resource set. It's also important to note that Eclipse has its own runtime resources, which are used and so when tracing these are included in the list as well.
By learning how to enable tracing and how to programmatically detect what objects are allocated, it will be possible to discover such leaks, or verify whether they have been fixed afterwards.