qwerty
qwerty

Reputation: 3869

Single thread executor with a cached thread

I am looking to perform a particular set of operations with one thread only. However, I cannot get Executors.newSingleThreadExecutor to work with a cached thread from a map.

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class ThreadTest {
    private final Callable<Boolean> task = new Callable() {
        @Override
        public Boolean call() {
            System.out.println("Ran");
            return Boolean.TRUE;
        }
    };

    //this prints the Callable output "Ran"
    @Test
    public void testVanilla() throws InterruptedException {
        ExecutorService service = Executors.newSingleThreadExecutor();
        service.submit(task);
        Thread.sleep(10);
    }

    //this does not print the Callable output "Ran"
    @Test
    public void testCached() throws InterruptedException {
        Map<String, Thread> map = new HashMap<>();
        Thread thread = new Thread("WORKER");
        thread.setDaemon(false);
        map.put("uniq", thread);
        ExecutorService service = Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return map.get("WORKER");
            }
        });

        service.submit(task);
        Thread.sleep(10);
    }
}

Is there something obviously wrong? I'm wondering why the executor did not work in case #2

Upvotes: 1

Views: 521

Answers (1)

Matthias
Matthias

Reputation: 1448

Your Thread has no Runable to invoke the callable. This Code works fine for me

    @Test
    public void testCached() throws InterruptedException {
        Map<String, Thread> map = new HashMap<>();
        ExecutorService service = Executors.newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {

                if (!map.containsKey("WORKER")) {
                    Thread thread = new Thread(r, "WORKER");
                    thread.setDaemon(false);
                    map.put("WORKER", thread);
                }

                return map.get("WORKER");
            }
        });

        service.submit(task);
        Thread.sleep(10);
    }

Upvotes: 1

Related Questions