Concurrent Programming : Make The Basics Correct !

Concurrent Programming two or more actions are run together simultaneously. And it may be turn out to nightmare if not done properly. Its something unforeseeable if proper care is not taken.

If mutable data is shared without proper precaution or, without proper synchronization then your application or even your life will turn out to be hell with production issues. The bad thing in concurrent programming is everything compiles fine without any errors or warning and one fine day your boss sends you a mail about a unexpected result faced by the client. And you are like what went wrong, my compiler friend never cautioned anything.

If multiple threads access the same mutable state variable without appropriate synchronization, your program is broken. There are three ways to fix it:

  •  Don’t share the state variable across threads;
  • Make the state variable immutable; or
  • Use synchronization whenever accessing the state variable.

A Thread can be stated as the flow of execution within a process.When we run a program, there is at least one thread of execution for its process.
In single core processor only one thread of execution takes place at particular instance of time where in multi core processor multiple thread of execution takes place in single instance of time.
Number of concurrent thread running for an application depends on the numbers cores associated with that process.
When designing thread-safe classes, good object-oriented techniques encapsulation, immutability, and clear specification of invariants are your best friends.

A class is thread-safe if it behaves correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
Stateless objects are always thread safe.

Make sure the following acts are ATOMIC :

  • 1. Act operations (like lazy initialization)
  • 2. Read modify write operations (like increment)

Synchronization also has another significant, and subtle, aspect: memory visibility. We want not only to prevent one thread from modifying the state of an object when another is using it, but also to ensure that when a thread modifies the state of an object, other threads can actually see the changes that were made.But without synchronization, this may not happen.

So these are the basic things we need to deal while working with Multi Core Processor.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s