Saturday, November 10, 2018

Java Concurrency - Thread Safety

Greetings!

What is thread safety?

When we have multiple threads accessing piece of code simultaneously without unwanted side effects we can say our code is thread safe. Correctness!!!

Synchronization

Synchronization allows to control the program flow and access to shared data for concurrently executing threads.

It is tempting to think synchronized is the only way to do this in Java but it is the primary mechanism which provides exclusive locking. volatile variable, explicit locks and atomic variables are other types.

We can synchronize using;
  • mutex lock - allow only one thread at a time to execute a specific section of code (critical section !!)
  • read/write lock - permit concurrent reads and exclusive writes to a protected shared resource.
  • condition variable - block threads until a particular condition is true.
  • semaphore - simply a variable which is a count (counting semaphore) or 0/1 switch (binary semaphore).

How to share mutable state between threads?

  • Don't share at all.
  • Make it immutable.
  • Use proper synchronization mechanism.

Tip :- Always try to use good programming techniques - Object oriented practices, encapsulation, immutability.
Stateless objects are always thread-safe!!!
Atomicity - Set of actions is atomic when all execute as a single operation.
Mutex (Mutual Exclusion) - At a given time only one thread can enter its critical section is called mutual exclusion.
Avoid holding the lock for lengthy computations or operations.

No comments:

Post a Comment