简体   繁体   English

设计和编写可以执行不同步或同步任务的任务调度程序

[英]Design and code a task scheduler that can take unsynchronized or synchronized tasks

This is an interview question, that means this could be done in a short time. 这是一个面试问题,这意味着可以在短时间内完成。 I thought to ask here because I cannot figure out what to do if I were asked. 我想在这里问一下,因为如果有人问我,我无法弄明白该怎么办。

"Design and code a task scheduler that can take unsynchronized or synchronized tasks" “设计和编写可以执行不同步或同步任务的任务调度程序”

Please use your imagination/assumption and share your thoughts and comments. 请用你的想象力/假设分享你的想法和评论。

This question is deliberately vague, it's suppose to show how good you are at designing and solving problems, what kind of assumptions do you make, how you justify them, etc. There is no single, good answer. 这个问题是故意模糊的,它假设你表现出你在设计和解决问题方面有多好,你做出了什么样的假设,你如何证明它们的合理性等等。没有单一的,好的答案。 It's a matter of approaching the problem. 这是一个解决问题的问题。

That being said here is my take: 这里说的是我的看法:

  1. My scheduler can take arbitrary Runnable or Callable<V> , I will implement ScheduledExecutorService because it seems to be a good abstraction for the problem. 我的调度程序可以采用任意的RunnableCallable<V> ,我将实现ScheduledExecutorService因为它似乎是一个很好的抽象问题。 I am using as many standard classes as I can to make API portable and easy to use. 我正在使用尽可能多的标准类来使API易于使用且易于使用。

  2. By unsychronized and synchronized I understand: safe to run concurrently and those that require exclusive lock. 通过 同步同步我理解:安全地同时运行和那些需要独占锁定。 Ie the scheduler is not allowed to run two synchronized tasks at the same time. 即,不允许调度程序同时运行两个同步的任务。

  3. The distinction between synchronized and unsychronized tasks will be made using marker interface. 将使用标记接口进行同步和非同步任务之间的区别。 Annotation is also fine, but harder to extract at runtime. 注释也很好,但在运行时更难提取。

  4. I won't give you the full implementation, but it'll probably wrap some standard ScheduledExecutorService with an additional synchronization for synchronized tasks. 我不会给你完整的实现,但它可能会包含一些标准的ScheduledExecutorService并为同步任务提供额外的同步。 I think ConcurrentMap<Class, Semaphore> would do. 我认为ConcurrentMap<Class, Semaphore>会这样做。 Before running tasks marked as synchronized I make sure no other synchronized task of the same time is running. 在运行标记为已同步的任务之前,请确保没有同时运行的其他同步任务。 I block and wait or reject (this can be configurable). 我阻止并等待或拒绝(这可以是可配置的)。

I would use an ExecutorService as it's built in and does most of the things you would want. 我会使用内置的ExecutorService并执行您想要的大部分操作。 It doesn't care if those tasks uses synchronized or not. 它不关心这些任务是否使用synchronized。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM