What is volatile keyword , c# (Csharp) and .NET interview questions ?

Posted By on May 5, 2019

one of the most unsung keyword not discussed keyword not talked keyword or not known keyword I will say is the volatile keyword now you know ninety percent time you will never use this keyword definitely but in case you are developing multi-threaded applications and if you want to handle concurrency in a better manner then definitely know this keyword is worth looking at so what we'll do is in order to understand the importance of this keyword you know let us first try to discuss what kind of problem do you face you know from from the concurrency issue you know in multi-threading and once we understand the problem you know then we'll try to see that how the volatile keyword will help us to solve the concrete problem in multi-threading so here's a sample code I have and this is basically a console application which I have created and in this console application the first thing you can see that there is a simple property a simple variable I will say here called as the loop variable and this loop variable is set to true by default and the next thing what I have in in this console application is a simple method here called as some thread you know and this method what it does is it takes actually a object now this object is nothing but basically the object of the program the class program you know in which we have a static void mean and what it does is it actually makes an infinite while loop okay until this loop is false okay so by default you can see that when the program actually initializes the loop is true and this method what it does is it actually makes an infinite loop here until you know this loop value actually becomes false and this some method this what it is some thread method right I am calling up in a multi-threaded manner you know from here so I'm calling the some thread method in a multi-threaded manner so you can see over here basically I have created the object of program class and I am creating a new thread and I am passing this program object which I have created it the test one that is my object to this thread and then this thread actually continuously moves in a loop so once the program starts this thread after that you know the program halts for 20 milliseconds over here and after 20 milliseconds it actually sets this loop value as false so what it means is when this loop value is set to false what it means is that you know this while loop which is running continuously will exit why because this loop will only run you know until this loop value is true so when this value is made false here it's actually acting on the same object test1 right because objects are by reference so what it means you know this while loop should exit and display me that this loop has been exited so in other words the way this program will flow is something like this first the thread will start and it should display us that you know this thread has started and you know it has entered the loop after that you know this loop will run continuously until this loop is set to false this loop variable is set to false after that you know when this value is set to false here you know the step two should execute and say that ok I've set the value to false now please do exit the loop and then what should happen is you know this while loop should exit and it should display us that you know this loop has exited so in other words first it should display step 1 enter the loop step 2 the value of the loop is set to false and step 3 you know that you know now it has exited the loop so now let's go and run this program in the release mode so in other words select and release here and run this program the release mode I'll explain you you know why I'm trying to run this program in a release mode term ok and let me do a control f5 right now let's see what happened so let me just set this whole thing here and the code here now if you see what has happened is ok first thing is you know this thread ran it spawned the thread and it showed me that okay it has entered the loop so it displayed me here that it has entered the loop second because it is multi-threaded so the static void main execution started moving ahead and after 20 milliseconds it actually said this underscore loop to false so you can see that the step two value is set to false now even though this value is set to false you know it is not exiting the loop because it has not printed this third step exited the loop so in other words you know this loop value which we have set to false here you know still this thread is thinking that it is true so in other words you know this variable data whatever what we have set here is not getting reflected on this thread so what exactly is happening let's try to understand now what was happening in the program there were two threads one thread you know which had that infinite while loop which was running okay with that some method you know which was running right which was running on a different thread which had that infinite while loop so there was one thread the second thread was the main thread the static void main thread you know where we were setting that loop value to false right now you know both of these threads were operating on that variable loop now this variable is stored into your main memory so here is a program running and then you have our main memory which is keeping a track of you know what variable values you have now initially when the program started right the the program actually set the loop value to true so your main memory was having the value as true now in order to increase efficiency these threads they do not directly access the main memory they have their own local memory so this thread one will have his own local memory must be lm1 you can say and this threat too will have his own memory called as must be lm-2 and both of these local memory you know which is related to every thread will have that loop variable okay and you know and there will be a sync you know which happens now and then between the main memory and the local memory of the threads now initially when you know the program start and it set the loop to true right then the loop value was true here the loop value was true here and the loop value was also true here right now as the program started running and it spawned thread 1 the loop was still true so this while loop was running continuously now in thread 2 when the value was set to false then it actually went and updated his own local storage he also went and he updated the main memory but what happened is you know this memory it was not updated so this thread was still having a stale value why because you know the main memory and local memory of the threads you know they have not gotten sync so because of this reason you know the updated data by thread 2 was not visible to thread 1 now remember you know the local memory which I've talked here LM 1 and LM 2 are my own notations ok it is you know it doesn't actually create some kind of local memory but you know it it since you can think about the know there is some kind of a virtual memory which is there for the thread even so that they can work faster on the data right but you know this is just my virtual thinking I have put here or I'll say this much as no virtual representation so that we can understand this topic better now these local memories you know why they are allocated separate is because when we spawn threads right it is very much possible that this thread can run on a different processor and this thread can run on a different processor and each of these processors actually have you know their own memory storage so there is one main memory and then there is local memories you know which are allocated for each thread and because the main memory and the local memory they don't get in sync so sometimes you know you can get weird results so what is the solution to this how can we ensure that you know when thread 1 accesses this variable you know we want to go and sync up the variable with the main memory so that we don't get weird results and that's where you know if you use we use this key word you know the key word which is not talked much in the.net world volatile so let's go ahead and let's fix up that program what we had created you know using the volatile keyword so as we have said in the previous part of the video that you know this loop variable the local loop variable data and the main memory loop variable data they are not getting in sync and that's why you know this while loop is running continuously here right so what we'll do is let's go and mark this as volatile now when you mark this as volatile what it means is that you know whenever this while loop runs right or whenever this while loop accesses the loop variable it will first go and sync this loop variable the local loop variable data with the main memory loop variable data and then it will actually do a while loop right so now if you run this program what will happen is it should first display a step 1 enter the loop in step 2 we set the value false because it is a volatile keyword because we are defined this variable as volatile this loop data gets sync the local variable as well as the main memory they get in sync and it actually exits this loop and we will be should see this step 3 so let me go and run control fi here so there it is so you can clearly see here that first the step one ran so in other words the loop started then the step two ran it said that value to false the loop variable value to false and in step three it actually exited the loop so in other words you know volatile keyword you will use in scenarios you know when you are doing multi-threaded applications and especially you know when you are accessing data which is you know updated concurrently by multiple threads and you know just to avoid problems or just to avoid this sinking problem between the between the local storage and the main storage you will use a volatile variable or the volatile keyword so the volatile keyword ensures you know that whichever variable did whichever variable you're accessing currently the data of the variable is up-to-date or it is in sync with the main variable data with the main memory what has been updated now whatever video you have seen right is just a glimpse of we have done so in case you are interested in our video package you can go to our site that is wqf on comm you can call on this number and you can ask the complete DVD package what we have so in this DVD package what we are done is basically we have covered almost everything what a.net developer wants so right from basics of asp.net object of programming is quill server to new technologies like WCF silverlight linq azure entity framework we also have uml architecture estimation project management there is a complete invoicing project end to end which is covered so that you can get a better feel of how to actually create projects in a systematic manner we have covered server products you know both for sharepoint 2007 as well as for 2010 we have lot of best practices video on SQL server etc so this complete package you know you can get from w luke respond comm if you're interested and you can call on this number and you can ask for the rates it's it's very decent rate what we have on the same in the same way you know as compared to the videos we also have one more product with us that is our interview question books so we have different kinds of interview question books you know right from from dot interview questions to SQL server interview questions sharepoint interview questions biztalk interview questions etc so in case you are interested in the books part you can can call on these numbers as per your location so you can see these numbers on the board at this moment so I hope that you keep enjoying the videos you keep seeing our site and I hope that you gain more knowledge thank you very much

Posted by Lewis Heart

This article has 18 comments

  1. in de loop, use Thread.Sleep(0); and then it's works also without the volatile keyword 🙂 .
    btw…. you have nice tutorials.

  2. Before scrolling down make sure you put Release instead Debug, it will not work on release even tho few people saying it works without volatile.

  3. To sum it up: System.Threading.Volatile. This class has a special Write and Read method, and those methods disable the compiler optimizations so you can force the correct order in your code. 

  4. I was asked to explain the significance of the term "volatile" at an interview for an internship. Six years later after watching this video I have a better idea of the meaning. Another tricky and not often used term is "extern". Both seem to be great interview questions.

  5. Hello dnfvideo,

    I love your videos and now have a goal of watching them all. I do have a question about volatile. As you mentioned it syncs the local memory (like say the cache on a processor) with the main memory. Do you think it is possible that your code example would ever hit the 3rd console write? In other words, would the local and main memories finally sync up. Of course, this is not the software behavior I would want – it's more of a hypothetical question.

    Thank you,


  6. yes you need to runin full compile mode. It will not work in f5 i.e. debug mode.

  7. It works as you mentioned when i set the app to "Release" mode and press CTRL + F5.
    But when i just press F5, it does work well without "Volatile" keyword. Any thoughts on this?

  8. I tried it by myself and it worked without the 'volatile' keyword. how come the same code behaves differently? I compiled it as .net 2.0 and 3.5 – same result.


Leave a Reply

Your email address will not be published. Required fields are marked *