Given that a static variable of a class takes only one memory location, is it shared by all threads of process? Or is one memory location for such a variable created for each of the running threads?
Also, if all threads share the same memory location, how can we ensure mutual exclusion?
A
staticvariable of aclassin a process will be shared between every thread contained in that process.You can verify this by creating a simple
classwith apublic staticfield, and then start up a couple ofThreadsand have them increment the variable and see what happens.If you want to ensure mutual exclusion you can make the variable private, and only allow access to it through methods that are defined using the
synchronizedkeyword.