Concurrency in Clean Code

  • Concurrency-related code has its own life cycle of development, change, and tuning.
  • Concurrency-related code has its own challenges, which are different from and often more difficult than non-concurrency-related code.
  • The number of ways in which miswritten concurrency-based code can fail makes it challenging enough without the added burden of surrounding application code.
  • Use the provided thread-safe collections.
  • Use the executor framework for executing unrelated tasks.
  • Use nonblocking solutions when possible.
  • Several library classes are not thread safe.
  • Treat spurious failures as candidate threading issues. — Don’t treat errors as one-offs, you should consider every single one of them, always.
  • Get your nonthreaded code working first. — This pretty much speaks for itself, multithreaded is pretty tough by itself and adding more bugs from a single thread code doesn’t help at all.
  • Make your threaded code pluggable. — This helps you run your code in several different configurations that help you cover more ground.
  • Make your threaded code tunable. — Allow the number of threads to be easily tuned. Consider allowing it to change while the system is running.
  • Run with more threads than processors. — With this practice you will more likely encounter code that is missing a critical section or causes deadlock
  • Run on different platforms. — Each OS has a different thread policy so it may happen that in some OS’s the code works just fine but in others it doesn’t.
  • Instrument your code to try and force failures. — You can instrument your code and force it to run in different orderings by adding calls to methods. Affect the order of execution and you will increase the odds of detecting a flaw.
  • You have to manually find appropriate places to do this.
  • How do you know where to put the call and what kind of call to use?
  • Leaving such code in a production environment unnecessarily slows the code down.
  • It’s a shotgun approach. You may or may not find flaws. Indeed, the odds aren’t with you.

The end

Concurrency is pretty hard but it can help the system a whole lot if we use it correctly, it’s a high risk high reward programming technique but we need to apply all this principles in order to always get the high reward. As always if you have any doubt feel free to contact me!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Victor Elizalde

Victor Elizalde

Software Engineer with a passion for sharing knowledge. Also, sports lover, musician, gamer, and a tremendous food fanatic.