Posted by: Cirilo Meggiolaro | 03/6/2009

Tip of the day #143 – volatile keyword

The volatile keyword is used to inform the compiler that a class field may be modified by more than one thread in runtime at the same time. Therefore, the compiler will not perform any optimization about it assuming that it is accessed by a single thread. The idea is to ensure that when your code accesses the field, always the most up-to-date value will be retrieved.

You may use the volatile keyword with primitive types such as byte, bool, char, float, int, sbyte, short, uint and ushort, reference types and others.

When it is used with Boolean flags (and only with Booleans), the thread synchronization is not necessary once an atomic operation is executed when reading or writing the value. If you use with different types you cannot rely on the fact that is thread-safe.

How to…

The syntax is pretty straightforward as shown below:

private volatile bool _myFlag;

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 )

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


%d bloggers like this: