문제

I use GPars for parallel processes which do background tasks. I use the following Service to start a new background thread.

  1. To save heap memory How can I restrict the number of background threads?

  2. How can I define a thread pool of n threads which handle my background tasks?

    import jsr166y.ForkJoinPool
    
    class TaskService {
    
    
    private pool = new ForkJoinPool()
    
    def executeAsync(args, closure = null) {
        if(!closure) {
            closure = args
            args = null
        }
    
        GParsPool.withExistingPool(pool) {
            closure.callAsync(args)
        }
    }
    }
    
도움이 되었습니까?

해결책

There is a ForkJoinPool(int) constructor that allows you to hint at the "amount of parallelism". My understanding is that in practice that controls the number of threads that the pool will use.


Do I get this right? A Service is a Singleton, so there is only one instance for my app. Does pool = new ForkJoinPool() will only instantiate once?

I'm not a grails expert :-). All I can say is that each time you instantiate the Java class ForkJoinPool you are creating a new pool.


When I use pool = new ForkJoinPool(4) and I call taskService. executeAsync(...) 5 times from my app. What happens in this case? Will the 5 tasks be executed from the 4 threads or will 4 task be executed and the last task will be blocked?

It depends what the tasks do. The basic idea of fork/join pool is that when a worker gets to a point where it would block the thread, it switches to another task. It only blocks the thread if there is no work that can be done.

So in your example, the first 4 tasks should start, and continue running until one of the tasks blocks. If / when that happens, the 5th task will start.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top