Thread Related Modifiers in Java

A computer program may have launched more than one process executing concurrently. This is called multithreaded programming. For example you have more than one process in a program executing concurrently, they may attempt to access a class element at the same time. There are a two modifiers that relate to such a situation.

volatile Modifier

The volatile modifier only applies to instance variables. The variables declared volatile are subject to asynchronous modifications. In other words, declaring a variable volatile informs the compiler that this variable may be changed unexpectedly by other parts of the program. So, the compiler takes some special precautions to keep this variable properly updated. The volatile variables are generally used in multithreaded or multiprocessor environments. The volatile modifier tells the accessing thread that it should synchronize its private copy of the variable with the master copy in the memory.



synchronized Modifier

The synchronized modifier is used in multithreaded programming to control access to critical sections in the program. It is used for thread safety in java multi-threaded programming.


Reference(s): SCJP Exam for J2SE 5  

No comments:

Post a Comment