Memory Barrier And Happens-Before

Memory barrier and Happens-Before are the most fundamental building block of visibility. Many developer don’t understand this concept or, rather skip it in hurry to climb the ladder to learn multithreading as early as possible. Let me tell you multithreading or concurrency are the something which needs your time. They want you to sit with them and spend as much as time with them as you do with your girl friend.

Lets start with Memory barrier, it is the process of copying the variable from local or cache memory to the main memory.

A change made to a variable by a thread will visible to another thread only if it crosses the memory barrier. Volatile and Synchronized forces the visibility across the threads.

First the changed is copied to register or cache and then copied to main memory by crossing memory barrier.

This sequence and order of crossing is called happens before i.e write happens before the read.

The write has to happens-before the read, meaning the writing thread has to cross the memory barrier before the reading thread does, for the change to be visible.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s