简体   繁体   中英

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. I am using as many standard classes as I can to make API portable and easy to use.

  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. I think ConcurrentMap<Class, Semaphore> would do. 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. It doesn't care if those tasks uses synchronized or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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