Is serial queue faster then synchronized block?

Viewed 32

Is serial queue faster then synchronized block?

I have two ways to achieve thread safety. I have implemented option-1 but, my supervisor wants me to implement option-2.

Option 1:

synchronized fun doSomething(task: Task){
    //task.do()
}

Option 2:

fun doSomething(task: Task){
    serialQueue.add(task)
}

Which approach is faster and why? And why two versions exist for single purpose?

1 Answers

In the first option the calling thread acquires the lock on the object that doSomething is called on, then executes the task, holding the lock until it’s done. If another thread wants to execute the same method on the same instance, that thread has to wait for the tasks run by other threads to finish before it can execute the method.

In the second option a thread drops the task in a queue. The thread isn’t held up waiting while the task executes.

Which option to use can be affected by several things, like how long the task takes, how important it is for the task to get done right now as opposed to letting it process through the queue, and whether you're blocking or non-blocking and how much other work that waiting thread could be doing for you.

Related