简体   繁体   中英

Correct way to access a queue (LinkedBlockingQueue) from ExecutorService

I have just realised LinkedBlockingQueue is a good solution in my case - I have a queue which is filled from time to time (but in very short time intervals). I want my ExecutorService to check as often as posiible for any objects appearing in this queue.

I am not sure what is the correct use of LinkedBlockingQueue now. Earlier, my code looked like:

public void launch(){

    ListeningExecutorService pool = 
            MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(threadNumber));

    while(true){
        if(!commandsQueue.isEmpty()){
            final ListenableFuture<String> future = pool.submit(new CommandWorker(commandsQueue.poll()));
            // [...]  
        }           
    }       
}

I am thinking about sth like:

public void launch(){
            ListeningExecutorService pool = 
            MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(threadNumber));

    while(true){
        Command newCommand = commandsQueue.take(); 
        final ListenableFuture<String> future = pool.submit(new CommandWorker(newCommand));
            // [...]  

    }       
}

The aim is, naturally, to make my ListeningExecutorService intercept new object as fast as possible. Is this a good way?

You're working too hard.

A blocking queue BLOCKS if there's nothing to read. Therefore if there is no command the command thread will simply pause and wait for the next command to be issued.

Your take command pops the first item off the queue. If there's no first item, the thread is paused. The if statement is unnecessary.

public void launch(){
        ListeningExecutorService pool = 
        MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(threadNumber));

    while(true){
        Command newCommand = commandsQueue.take(); 
        final ListenableFuture<String> future = pool.submit(new CommandWorker(newCommand));
    }       
}

Why do you use the queue at all? Instead of "commandsQueue.put(command)", do "pool.submit(new CommandWorker(command))" directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM