Design Patterns for Multithreading

Ankit Zalani picture Ankit Zalani · Jun 23, 2013 · Viewed 27.9k times · Source

Multitasking seems to be a disaster at times when big projects crashes due to shared mutation of I would say shared resources are accessed by multiple threads. It becomes very difficult to debug and trace the origin of bug and what is causing it. It made me ask, are there any design patterns, which can be used while designing multithreaded programs?

I would really appreciate your views and comments on this and if someone can present good design practices which can be followed to make our program thread safe, it will be a great help.

Answer

Ibrahim Najjar picture Ibrahim Najjar · Jun 23, 2013

@WYSIWYG link seems to have a wealth of useful patterns but i can give you some guidelines to follow. The main source of problems with Multi-Threaded programs is Update Operations or Concurrent Modification and some of the less occurring problems are Starvation, Deadlocks , etc which are more deadly if i may say, so to avoid these situations you can:

  • Make use of the Immutable Object pattern, if an object can't be modified after creation then you can't have uncoordinated updates and as we know the creation operation itself is guaranteed to be atomic by the JVM in your case.
  • Command Query Segregation Principle: that is separate code that modifies the object from code that reads them because reading can happen concurrently but modification can't.
  • Take huge benefit of the language and library features you are using such as concurrent lists and threading structures because they are well designed and have good performance.
  • There is a book (although an old one) but with very good designs for such systems, it is called Concurrent Programming in Java.