开发者

Sequencing operations on specific object in a ThreadPool Executor

开发者 https://www.devze.com 2023-02-15 16:45 出处:网络
We have a ThreadPoolExecutor that pulls tasks off a queue for execution.For a given type of object, ex. user, we can have parallel operations occurring across different instances. However, operations

We have a ThreadPoolExecutor that pulls tasks off a queue for execution. For a given type of object, ex. user, we can have parallel operations occurring across different instances. However, operations on a single instance have to be do开发者_如何学Cne in order.

The thread pool cannot guarantee this as two items inserted consecutively can be done in a non-deterministic order due to thread scheduling. I do not see a means to accomplish this is the standard java libraries. Is there a 3rd party solution that provides this capability.

We can implement this ourselves, but it is a rather complex issue and I would rather go with a hardened solution at this point.

Thanks


What about creating your ThreadPoolExecutor with a PriorityBlockingQueue. The "priority" can be defined as a Comparator which could differentiate by instance id or something that allows you to group similar items.


You can create a queue for each object and add a task to the ThreadPoolExecutor to perform the next task for that object. To ensure tasks are not performed concurrently on an object you can lock the object or the queue when you do this.

0

精彩评论

暂无评论...
验证码 换一张
取 消