我有一个GUI类,只需单击一个按钮就可以创建并执行SwingWorker子类。 SwingWorker类保存对主要的引用,以告诉它更新进度条。 SwingWorker类实例化ExecutorService.FixedThreadPool并提交一个返回ArrayList的数字m Callable子类。运行时,Mac Activity Monitor记录n *初始内存,其中n是到目前为止执行的线程数,并且该过程占用了大部分cpu。运行1线程对4或甚至8的影响,m> 1。如果有的话,n也是速度的10%。当创建一个新的Callable(名为DetectFruitTask的子类)并传入了许多参数时,我是否创建了一个强大的引用来使GC保持它的运行状态?
以下是可能引起关注的一行(注意我没有保留对返回的Callable对象的引用,但仍会导致内存过载):
executor.submit(new FruitDetectTask((int[])stack.getProcessor(i).getPixels(), sobel, width, height, lumaWeight, sdWeight, threshold));
这是实际的Callable:
public class FruitDetectTask implements Callable<ArrayList<FruitObject>> {
private int[] pixels;
private float[][] sobel;
private float lumaWeight;
private float sdWeight;
private int width;
private int height;
private float threshold;
public FruitDetectTask(int[] pixels, float[][] sobel, int width, int height, float lumaWeight, float sdWeight, float threshold) {
this.pixels = pixels;
this.sobel = sobel;
this.width = width;
this.height = height;
this.lumaWeight = lumaWeight;
this.sdWeight = sdWeight;
this.threshold = threshold;
}
@Override
public ArrayList<FruitObject> call() throws Exception {
float[] edgeIntensities = EdgeDetector.calculateEdgeIntensities(pixels, sobel, width, height, lumaWeight, sdWeight);
byte[] edges = new byte[edgeIntensities.length];
for (int j = 0; j < edgeIntensities.length; j++) {
if (edgeIntensities[j] > threshold) {
edges[j] = (byte)0;
} else {
edges[j] = (byte)255;
}
}
ArrayList<FruitObject> fruits = FruitDetector.detect(edges, width, height);
return fruits;
}
}