YoungPetr
YoungPetr

Reputation: 51

Spring rest api application with backgorund worker thread

I am building an application with rest api using Spring. I need the possibility for rest api methods to add tasks (just objects) into a queue and background worker thread which will wait when the queue is empty or do tasks one by one when it is not empty. It is absolutely necessary to execute tasks one by one and they can take from 1s up to several minutes. There is no need to wait for and send result via rest api, only information that the task has been .started

Basically my idea is something like (not how I would code it, I know this can be done better using concurrency package and executors...):

public class Worker implements Runnable {

    private Queue<...> queue;

    public addTask(... task) {
        this.queue.add(task);
        this.notify();
    }

    @Override
    public void run(){
        check task queue
           - wait() if empty
           - execute task if not empty
    }

}

Nothing I have tried works in combination with spring.

I have some java knowledge and I have already made some desktop apps using concurrency, but no spring experience, so i just need to point to the right direction.

Can this be done using asynchronous methods (@Async)? Or would it be acceptable to create synchronous thread (component) which will check queue periodically?

Thank you for ideas.

Upvotes: 1

Views: 1019

Answers (1)

Leon
Leon

Reputation: 12481

You can do this using a BlockingQueue https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/BlockingQueue.html

I'm not sure about your system constraints, but a solution with an embedded queue will not scale out very well. If your service become constraint you need to run multiple instances you can end in a situation where calls to one server takes longer than calls to the other.

If you are going to do this in combination with Spring you need to create the BlockingQueue as a Bean so that you can inject it into your worker and your controllers

Upvotes: 1

Related Questions