Asynchronous execution in BlockingQueue
Asked Answered
S

0

1

I am using Java collections BlockingQueue for data processing. The current code looks like

while(true){
    if(queue.size() > 0)
        handle(queue.take())
}

Is there a way (in Java or other frameworks) where I can process it asynchronously, like,

queue.setHandler(new Handler<E>());

somewhere down the class..

class Handler implements IHandler<E>{
    void handle(E e){
        handle(e)
    }
}
Starks answered 26/9, 2015 at 2:54 Comment(8)
This is awfully broad, but you may be looking for RxJava.Roderich
ExecutorService executorService = Executors.newFixedThreadPool(10); executorService.execute(new Runnable() { public void run() { System.out.println("Asynchronous task"); } }); executorService.shutdown();Sparke
visit tutorials.jenkov.com/java-util-concurrent/executorservice.html.Sparke
@sunrise76 - ES is not an option, the approach is not to create threads, framework should call the handler synchronously, similar to listener frameworkStarks
Your question says handling asynchronous events with blocking queue. ThreadpoolExecutor which takes blocking queue as parameter in constructor will do the same. If you don't want to create threads, set max limit as one. Blocking queue events will be processed one by one.Sparke
Check if this question is useful for you: #30783111Sparke
If you look inside a framework which executes messages asynchronously as you wish, you'll find it does it in a way you do it now. So that framework only hides what really happens. Why do you need such a framework?Cirenaica
The line if(queue.size() > 0) is excessive. It consumes CPU time but does not add any useful functionality. It can be safely removed.Cirenaica

© 2022 - 2024 — McMap. All rights reserved.