Minimizing Critical Sections
When using mutexes, an important principle is to minimize the scope of critical sections. The larger the critical section, the longer other threads have to wait, resulting in worse concurrency performance.
A good pattern is: first complete time-consuming calculations locally, and only hold the lock for the brief moment when shared data needs to be accessed. This can significantly reduce lock contention and improve the program's concurrency performance.
In the code on the right, each worker thread constructs a message string locally (a relatively time-consuming operation) and only enters the synchronized block when adding a message to the shared list. This is much more efficient than holding the lock during the entire message construction period.
The output will show messages from different workers, and the order may vary due to concurrent scheduling.
Try moving message construction inside the synchronized block - while the result will be the same, performance will decrease.