My application used multiple Hashmaps to store Color and Image objects that were randomly generated whenever a new Key came up (which could be an infinite amount).
To reduce memory usage I am using a Hashfunction to limit the amount of randomly generated Colors and Images to 229. Weirdly enough when I was storing virtually infinite Colors and Images, the program did run without major issues (except for the leak of course).
Now that I'm trying to re-use a limited set of Objects strangely after a few seconds I keep getting the exception :
org.eclipse.swt.SWTException: Failed to execute runnable (org.eclipse.swt.SWTError: No more handles)
The generation of the maps looks something like this:
static Map<Integer, Color> color = new Hashtable<>();
private static final int MAX_COLORS = 229;
private static void generateColor(String typeName) {
if (mapping.containsKey(typeName)) {
return;
}
Color c = generateRandomColor(typeName);
color.put(typeNameHash(typeName), c);
}
private static Color generateRandomColor(String typeName) {
if(color.containsKey(typeNameHash(typeName))){
return color.get(typeNameHash(typeName));
}
int red = random.nextInt(255);
int green = random.nextInt(255);
int blue = random.nextInt(255);
return new Color(Display.getCurrent(), red, green, blue);
}
private static int typeNameHash(String typeName){
return Math.abs(typeName.hashCode())%MAX_COLORS;
}
How is it possible that now, that I should have less objects, I'm running into this kind of exception so fast?
Thanks in advance!
The solution to my issue here was, that I was still using the Strings as keys, instead of calling the hash-function on the strings in some instances. Since HashMaps take Objects-type for keys the compiler did not warn me about that.
Checking all code parts where I inserted into the Hashmap and making sure the hash-function was used everywhere resolved the issue.