Вопрос

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top