バグを見つけられますか?これにより、がスローされjava.lang.OutOfMemoryError
ます。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestTheads {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(1);
while(true) {
executorService.submit(new Runnable() {
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
});
}
}
}
バグは、無視しているオブジェクトを返すため、executorService.submit()
の代わりに呼び出すことです。を使用すると、このプログラムは実際には永久に実行されます。executorService.execute()
submit()
Future
execute()
ただし、 :execute()
を使用する場合のように、メソッドを持つという贅沢が常にあるとは限りません。ScheduledExecutorService
public static void main(String[] args) {
// this will FAIL because I ignore the ScheduledFuture object
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
while(true) {
executorService.scheduleWithFixedDelay(new Runnable() {
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}, 1, 1, TimeUnit.SECONDS);
}
}
何も返さず、計算するだけのタスクで何をすべきでしょうか?
どんなアイデアでもありがたいです!
編集:ThreadPoolExecutor
spurge()
は有望に見えましたが、キャンセルされたタスクのみを削除します。