Reputation: 163
I am working on a custom text field for a touch device and this text field is to be used in games. This custom text field is a class and has a variable in which the keypad image is stored which is static variable, if I have to display 2 text field in one page(screen) I’ll have to create 2 objects of the text field class and since the keypad image is stored in a static variable it would be shared by both the objects, now I want to know, if any objects are created of the custom keypad class, are these objects(memory) being referenced by any variable, if not I want to free the image memory and reload it when a new object is created.
Upvotes: 4
Views: 153
Reputation: 11715
If you have access to WeakReference
, you could keep a static WeakReference
to the image in your class, and have a non-static (strong) reference in instances of your class:
public class CustomTextField {
// Only necessary if multiple threads can create UI elements
private static final Object lock = new Object();
private static WeakReference<Image> keypadRef;
private final Image keypad;
public CustomTextField() {
this.keypad = loadKeypad();
}
private static Image loadKeypad() {
Image keypad = null;
// Same comment as above: you don't need the lock if the UI elements are
// not created in multiple threads.
synchronized (lock) {
if (keypadRef != null) {
keypad = keypadRef.get();
}
// Either there was no existing reference, or it referenced a GCed
// object.
if (keypad == null) {
keypad = new Image();
keypadRef = new WeakReference(keypad);
}
}
return keypad;
}
}
That makes the keypad image eligible to garbage collection as soon as there are no instances referencing it, otherwise it's kept around and shared between instances.
Upvotes: 2
Reputation: 8671
IMO for a Java ME app you should have enough understanding of the codebase to know for yourself when memory-hungry objects like images can be freed.
Upvotes: 1