How to make calling a Method as a background process in java

后端 未结 6 682
无人共我
无人共我 2021-01-16 06:50

In my application , I have this logic when the user logins , it will call the below method , with all the symbols the user owns .

public void sendSymbol(Stri         


        
6条回答
  •  失恋的感觉
    2021-01-16 07:22

    Something like this is what you're looking for.

        ExecutorService service = Executors.newFixedThreadPool(4);
        service.submit(new Runnable() {
            public void run() {
                sendSymbol();
            }
        });
    

    Create an executor service. This will keep a pool of threads for reuse. Much more efficient than creating a new Thread each time for each asynchronous method call.

    If you need a higher degree of control over your ExecutorService, use ThreadPoolExecutor. As far as configuring this service, it will depend on your use case. How often are you calling this method? If very often, you probably want to keep one thread in the pool at all times at least. I wouldn't keep more than 4 or 8 at maximum.

    As you are only calling sendSymbol once every half second, one thread should be plenty enough given sendSymbols is not an extremely time consuming routine. I would configure a fixed thread pool with 1 thread. You could even reuse this thread pool to submit other asynchronous tasks.

    As long as you don't submit too many, it would be responsive when you call sendSymbol.

提交回复
热议问题