Question

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.

Was it helpful?

Solution

@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.

OTHER TIPS

Design patterns are used to solve a specific problem. If you want to avoid deadlocks and increase debugging, there are some dos and donts

  1. User thread-safe library. .Net java, C++ have their own thread safe libraries. Use them. Don't try to create your own data structures.

  2. If you are using .Net, try Task instead of threads. They are more logical and safe.

You might wanna look at list of some Concurrency related patterns

http://www.cs.wustl.edu/~schmidt/patterns-ace.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top