How can I find out if there are any class (memory) objects referenced or not in j2me?

I am working on a custom text field for a touch device, and this text field should be used in games. This custom text field is a class and has a variable that stores the keyboard image, which is a static variable if I need to display 2 text fields on one page (screen). I need to create 2 objects of the text field class, and since the keyboard image is stored in a static variable that it will be shared by both objects, now I want to know if any objects are created from the user keyboard class, are these objects (memory) a reference to any variable, if not I want to free the memory of the image and reload it when creating a new object.

+4
source share
2 answers

If you have access to WeakReference , you can save a static WeakReference image in your class and have a -static (strong) link in cases 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; } } 

This makes the keyboard image available for garbage collection as soon as there are no instances that reference it, otherwise it is stored and shared between the instances.

+2
source

IMO for a Java ME application, you should have a good understanding of what the code base itself needs to know when hungry objects such as images can be freed.

+1
source

Source: https://habr.com/ru/post/1439746/


All Articles