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:
My scheduler can take arbitrary
RunnableorCallable<V>, I will implementScheduledExecutorServicebecause 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.By unsychronized and synchronized I understand: safe to run concurrently and those that require exclusive lock. I.e. the scheduler is not allowed to run two synchronized tasks at the same time.
The distinction between synchronized and unsychronized tasks will be made using marker interface. Annotation is also fine, but harder to extract at runtime.
I won’t give you the full implementation, but it’ll probably wrap some standard
ScheduledExecutorServicewith an additional synchronization for synchronized tasks. I thinkConcurrentMap<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).