<p>I am re-factoring some code and am wondering about the use of a <code>lock</code> in the instance constructor.</p>

<pre><code>public class MyClass {

    private static Int32 counter = 0;
    private Int32 myCount;

    public MyClass() {

        lock(this) {
            counter++;
            myCount = counter;
        }
    }
}
</code></pre>

<p>Please confirm</p>

<ol>
<li>Instance constructors are thread-safe.</li>
<li>The lock statement prevents access to that code block, not to the static 'counter' member.</li>
</ol>

<p>If the intent of the original programmer were to have each instance know its 'count', how would I synchronize access to the 'counter' member to ensure that another thread isn't new'ing a <code>MyClass</code> and changing the count before this one sets its count?</p>

<p><em>FYI - This class is not a singleton. Instances must simply be aware of their number.</em></p>

[{'answer_id': 41801, 'author': 'Nick Berardi', 'author_id': 17, 'author_profile': 'https://Stackoverflow.com/users/17', 'pm_score': 2, 'selected': False, 'text': "<p>I'm guessing this is for a singleton pattern or something like it. What you want to do is not lock your object, but lock the counter while your are modifying it.  </p>\n\n<pre><code>private static int counter = 0;\nprivate static object counterLock = new Object();\n\nlock(counterLock) {\n    counter++;\n    myCounter = counter;\n}\n</code></pre>\n\n<p>Because your current code is sort of redundant. Especially being in the constructor where there is only one thread that can call a constructor, unlike with methods where it could be shared across threads and be accessed from any thread that is shared.</p>\n\n<p>From the little I can tell from you code, you are trying to give the object the current count at the time of it being created. So with the above code the counter will be locked while the counter is updated and set locally. So all other constructors will have to wait for the counter to be released.</p>\n"}, {'answer_id': 41804, 'author': 'hakan', 'author_id': 3993, 'author_profile': 'https://Stackoverflow.com/users/3993', 'pm_score': 2, 'selected': False, 'text': "<p>You can use another static object to lock on it. </p>\n\n<pre><code>private static Object lockObj = new Object();\n</code></pre>\n\n<p>and lock this object in the constructor.</p>\n\n<pre><code>lock(lockObj){}\n</code></pre>\n\n<p>However, I'm not sure if there are situations that should be handled because of compiler optimization in <code>.NET</code> like in the case of java</p>\n"}, {'answer_id': 41813, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 0, 'selected': False, 'text': '<p>I think if you modify the <a href="http://en.wikipedia.org/wiki/Singleton_pattern#C.23" rel="nofollow noreferrer">Singleton Pattern</a> to include a count (obviously using the thread-safe method), you will be fine :)</p>\n<h3>Edit</h3>\n<p>Crap I accidentally deleted!</p>\n<p>I am not sure if instance constructors <em>ARE</em> thread safe, I remember reading about this in a design patterns book, you need to ensure that locks are in place during the instantiation process, purely because of this..</p>\n'}, {'answer_id': 41816, 'author': 'Anthony Mastrean', 'author_id': 3619, 'author_profile': 'https://Stackoverflow.com/users/3619', 'pm_score': 0, 'selected': False, 'text': '<p>@<a href="https://stackoverflow.com/questions/41792/instance-constructor-sets-a-static-member-is-it-thread-safe#41795">Rob</a></p>\n\n<p>FYI, This class may not be a singleton, I need access to different instances. They must simply maintain a count. What part of the singleton pattern would you change to perform \'counter\' incrementing?</p>\n\n<p>Or are you suggesting that I expose a static method for construction blocking access to the code that increments and reads the counter with a lock.</p>\n\n<pre><code>public MyClass {\n\n    private static Int32 counter = 0;\n    public static MyClass GetAnInstance() {\n\n        lock(MyClass) {\n            counter++;\n            return new MyClass();\n        }\n    }\n\n    private Int32 myCount;\n    private MyClass() {\n        myCount = counter;\n    }\n}\n</code></pre>\n'}, {'answer_id': 41820, 'author': 'Rob Cooper', 'author_id': 832, 'author_profile': 'https://Stackoverflow.com/users/832', 'pm_score': 3, 'selected': True, 'text': '<p>@ajmastrean</p>\n<p>I am not saying you should use the singleton pattern itself, but adopt its method of encapsulating the instantiation process.</p>\n<p>i.e.</p>\n<ul>\n<li>Make the constructor private.</li>\n<li>Create a static instance method that returns the type.</li>\n<li>In the static instance method, use the lock keyword before instantiating.</li>\n<li>Instantiate a new instance of the type.</li>\n<li>Increment the count.</li>\n<li>Unlock and return the new instance.</li>\n</ul>\n<h3>EDIT</h3>\n<p>One problem that has occurred to me, if how would you know when the count has gone down? ;)</p>\n<h3>EDIT AGAIN</h3>\n<p>Thinking about it, you could add code to the destructor that calls another static method to decrement the counter :D</p>\n'}, {'answer_id': 41852, 'author': 'Mike Schall', 'author_id': 4231, 'author_profile': 'https://Stackoverflow.com/users/4231', 'pm_score': 4, 'selected': False, 'text': '<p>If you are only incrementing a number, there is a special class (Interlocked) for just that...</p>\n<p><a href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.increment.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.threading.interlocked.increment.aspx</a></p>\n<blockquote>\n<p>Interlocked.Increment Method</p>\n<p>Increments a specified variable and stores the result, as an atomic operation.</p>\n</blockquote>\n<pre><code>System.Threading.Interlocked.Increment(myField);\n</code></pre>\n<p>More information about threading best practices...</p>\n<p><a href="http://msdn.microsoft.com/en-us/library/1c9txz50.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/1c9txz50.aspx</a></p>\n'}, {'answer_id': 41961, 'author': 'Andrew', 'author_id': 1948, 'author_profile': 'https://Stackoverflow.com/users/1948', 'pm_score': 2, 'selected': False, 'text': '<p>The most efficient way to do this would be to use the Interlocked increment operation. It will increment the counter and return the newly set value of the static counter all at once (atomically)</p>\n\n<pre><code>class MyClass {\n\n    static int _LastInstanceId = 0;\n    private readonly int instanceId; \n\n    public MyClass() { \n        this.instanceId = Interlocked.Increment(ref _LastInstanceId);  \n    }\n}\n</code></pre>\n\n<p>In your original example, the lock(this) statement will not have the desired effect because each individual instance will have a different "this" reference, and multiple instances could thus be updating the static member at the same time.</p>\n\n<p>In a sense, constructors can be considered to be thread safe because the reference to the object being constructed is not visible until the constructor has completed, but this doesn\'t do any good for protecting a static variable.</p>\n\n<p>(Mike Schall had the interlocked bit first)</p>\n'}]
['https://Stackoverflow.com/questions/41792', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3619/']