限制生成的 SWT 对象数量后不再处理

No more handles after limiting amount of generated SWT objects

我的应用程序使用多个 Hashmap 来存储 Color 和 Image 对象,这些对象在出现新 Key 时随机生成(可能是无限量)。

为了减少内存使用,我使用哈希函数将随机生成的颜色和图像的数量限制为 229。 奇怪的是,当我存储几乎无限的颜色和图像时,该程序 运行 没有出现重大问题(当然除了泄漏)。

现在我正尝试在几秒钟后奇怪地重新使用一组有限的对象,但我一直收到异常:

org.eclipse.swt.SWTException: Failed to execute runnable (org.eclipse.swt.SWTError: No more handles)

生成的地图看起来像这样:

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;
    }

我现在怎么可能拥有更少的对象,我这么快就运行陷入这种异常?

提前致谢!

我的问题的解决方案是,我仍然使用字符串作为键,而不是在某些情况下对字符串调用散列函数。 由于 HashMaps 采用对象类型作为键,因此编译器没有警告我。

检查我插入 Hashmap 的所有代码部分并确保在所有地方都使用哈希函数解决了这个问题。