An analysis of a hidden bug in generic implementation that does not properly lock the reference type

Source: Internet
Author: User

Recently, I have seen dotNetDR _'s reply in this article, reminding me of a real case. Next I will briefly talk about this hidden defect that is not easily discovered about the lock reference type.

The code in a class library encapsulates a very simple generic class for threads to safely execute a specific type of method. several lines of code can be done:

    public class ConcurrentObjectExecutor<T> where T : IDisposable, new()    {        public void Start()        {            T obj = new T();            lock (obj)            {                Console.WriteLine(obj.ToString());                //do sth            }        }    }

 

To design this class, it is estimated that the thread can safely execute a method for the types inherited from a specific interface. If the generic type T is a class, the program runs without any problems and ensures thread security.

However, we know that generic constraints only inherit from interfaces and new, and T is far from a class. structure (struct) can inherit interfaces or new. For example, to customize a structure:

    struct OrderMessger : IDisposable    {        public void Dispose()        {        }    }

 

The following code can be compiled and won't throw an exception during the runtime (if you don't look at the context, most callers estimate that it will let it pass, which may become a potential hidden and deep bug in the future):

    var executor = new ConcurrentObjectExecutor<OrderMessger>();     executor.Start();

 

Obviously, the above generic program seems to have locked a structure, that is, locking a value type. However, we know that the lock object specified by the lock keyword must be of the reference type. In the above example, the actual situation is that the structure instance obj is implicitly converted into a reference object instance (that is, a new instance is generated for each boxing ), this lock is meaningless, because under the multi-thread condition, the obj for thread contention is no longer the same instance (reference) specified ).

The funny thing is that directly write the following code and report errors directly on the lock statement during compilation (checking during compilation is really helpful, why does ms not make generic detection smarter ?) :

           var obj = new OrderMessger();            lock (obj)            {            }

 

Error 1 "OrderMessger" is not the reference type required by the lock statement

The solution is also very simple. The generic constraint must be a class on the basis of the original one.

Conclusion: In the design of the class library, the more common things are considered, the more thoughtful the application scenario is. thread security is a very important and essential link. During the thread security implementation process, if you do not have a deep understanding of the multi-Thread synchronization primitive, it is likely to design implementation with potential defects. MSDN's call and description of Thread Safe is worth profound learning and reference by class library developers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.