So I have been checking possibilities of using Closeable
interface with ExecutorService
. Then I saw Lukas answer here which is simply using method reference:
ExecutorService service = Executors.newSingleThreadExecutor();
try (Closeable close = service::shutdown) {
}
So i have been digging around and wanted to initialize service also in try block:
@Test(expected = RejectedExecutionException.class)
public void singleThreadTest() throws Exception {
ExecutorService es = null;
try (Closeable closeable = (es = Executors.newSingleThreadExecutor())::shutdown){
es.execute(()->System.out.println("executed " + Thread.currentThread().getId()));
}
System.out.println("executed " + Thread.currentThread().getId());
System.out.println(es.isShutdown());
es.execute(()->{});
}
This part quite ok eclipse a bit confused but if there is exception it will be supressed I believe, then I have tried:
@Test(expected = RejectedExecutionException.class)
public void singleThreadTest() throws Exception {
ExecutorService es = null;
try (Closeable closeable = es::shutdown){
es = Executors.newSingleThreadExecutor();
es.execute(()->System.out.println("executed " + Thread.currentThread().getId()));
}
System.out.println("executed " + Thread.currentThread().getId());
System.out.println(es.isShutdown());
es.execute(()->{});
}
For this code block I get NullPointerException
but the code block successfully executed (new thread created but at close() phase I got exception). I notice that while I was declaring :
Closeable closeable = es::shutdown
es has to be (effectively) final, this issue just occurs with double colon operator. i.e. below one doesnt compile:
try (Closeable closeable = new Closeable() {
@Override
public void close() throws IOException {
es.shutdown();
}
}){
Is this a bug? What is the cause of this? *Method reference impl? *IDE *JVM (oracle - debian)?
Followup:
@Test(expected = RejectedExecutionException.class)
public void singleThreadTest() throws Exception {
ExecutorService es = null;
es = Executors.newSingleThreadExecutor();
es = Executors.newSingleThreadExecutor();
es = null;
try (Closeable closeable = ()->es.shutdown();){
es = Executors.newSingleThreadExecutor();
es.execute(()->System.out.println("executed " + Thread.currentThread().getId()));
}
System.out.println("executed " + Thread.currentThread().getId());
System.out.println(es.isShutdown());
es.execute(()->{});
}
This code doesnt compile but this does:
@Test(expected = RejectedExecutionException.class)
public void singleThreadTest() throws Exception {
ExecutorService es = null;
es = Executors.newSingleThreadExecutor();
es = Executors.newSingleThreadExecutor();
es = null;
try (Closeable closeable = es::shutdown;){
es = Executors.newSingleThreadExecutor();
es.execute(()->System.out.println("executed " + Thread.currentThread().getId()));
}
System.out.println("executed " + Thread.currentThread().getId());
System.out.println(es.isShutdown());
es.execute(()->{});
}