本文介绍了从Java并发迁移到Scala并发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有一个相当标准的机制来解决问题:




  • 工作项目必须安排在特定时间执行

  • 每个工作项目必须等待条件成为真实

  • 工作项目应可取消



我使用的解决方案如下:


  1. 有一个单线程调度程序来安排我的工作

  2. ExecutorService (可能是多线程的)

  3. 然后将实际工作提交给 ExecutorService 。返回的 Future 被缓存在地图中。完成服务用于在工作完成时从缓存中删除未来

  4. 通过缓存的期货可以取消项目

当然,我的执行器需要至少与我期望的阻塞工作项数一样大,但这在实践中不是问题。



现在我在Scala中编码并使用actor框架。假设我的工作项可以被封装在发送给actor的事件中:


  1. 我将使用什么机制来安排工作项具体时间?

  2. 如果工作项是发送给actor的事件,那么如何确保后备线程池大于可以同时阻止的项目数

  3. 如何导致先前计划的工作项目被取消?


解决方案

我将使用一个java.util.concurrent.ScheduledExecutorService。

这使我成为一个可以阻止的项目设计,击败并行化的努力。尝试最小化或消除阻塞和全局状态。这些是可组合性和可扩展性的障碍。例如,考虑有一个专用线程等待文件到达,然后将事件触发给actor。或者查看java.nio的异步非阻塞I / O。



我不完全了解你的要求,但似乎你可以有一个线程/ actor寻找I / O事件。然后,作为您计划的工作项,计划创建非阻塞的actor的效果。让这些演员注册自己与I / O线程/ actor以接收他们关心的I / O事件的消息。

I would use a java.util.concurrent.ScheduledExecutorService.

This strikes me as a design that defeats the effort of parallelisation. Try to minimise or eliminate blocking and global state. These are barriers to composability and scalability. For example, consider having a single dedicated thread that waits for files to arrive and then fires events off to actors. Or look at java.nio for asynchronous non-blocking I/O.

I don't fully understand your requirements here, but it seems like you could have a single thread/actor looking for I/O events. Then as your scheduled "work items", schedule effects that create non-blocking actors. Have those actors register themselves with the I/O thread/actor to receive messages about I/O events that they care about.

ScheduledExecutorService returns Futures. What you have is not a bad design in that regard. Collect them in a Map and call future.cancel().

这篇关于从Java并发迁移到Scala并发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-26 18:55
查看更多