Why using a static variable is a bad idea to prevent multiple threads from entering a method at the same time
Often people do this, where we check a boolean value, if it is true, either sleep or return expecting that it will never happen that multiple threads will enter beyond this "gate".
Not true.
This is coded under the mistaken impression that every line of higher language code is executed as one statement and hence, it will never go beyond those lines if the next line sets the variable to true.
Because usually one line of higher language code even an i++ maps to multiple CPU instructions, given an adequately busy environment, this code will no longer "protect" the method. The only way to protect it is to use the lock statement.
Not true.
This is coded under the mistaken impression that every line of higher language code is executed as one statement and hence, it will never go beyond those lines if the next line sets the variable to true.
Because usually one line of higher language code even an i++ maps to multiple CPU instructions, given an adequately busy environment, this code will no longer "protect" the method. The only way to protect it is to use the lock statement.
Comments
Post a Comment