문제

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