After .NET 4.0, a secure lazy loading type was provided in the .NET FrameworkLazy Lazy is able to operate in a multi-threaded environment, guaranteedGetValueThe function is executed only once, thus implementingSingleton mode
In the past, we used quadratic judgment locks to implement singleton patterns, or to utilize static initialization functions of classes With the Lazy type, this process is simplified and the performance is better
When Lazy is created, you can specify the thread installation mode, there are currently two modes,PublicationOnly,ExcutionAndPublication
PublicationOnly mode
1. Run the initialization function and box it into an internalBoxtype, solve the problem of null value judgment, if the case has been created, it will return null,The process is thread-insecure
2. Determine whether the m_boxed is empty, m_boxed is the field saved by value, if it is equal to empty, it is set to boxed, this method can ensure atomicity,The process is thread-safe
3. If CreateValue returns empty, it means that other threads have already created instances, then set to already created instances
4. Mark the initialization method as initialized, which usually occurs in the case of concurrent run, and run CreateValue multiple times
PublicationOnlymode is used based onInterlocked.CompareExchange, this class contains atomicity methodsCAS(Compare and swap)
CAS is implemented using atomic instructions provided by the CPU, and different runtime versions may have different implementations Interlocked specific implementation In the native method, interested friends can check the specific implementation through coreclr/jvm code
In this mode,A singleton function may run multiple times, but in the end it is guaranteed that only one instance will be obtained
ExcutionAndPublication mode
ExcutionAndPublicationmode used in the modeVolatile+Monitor,MonitorIt islockThe implementation of the statement, the Monitor implementation in the native code, is a heavyweight lock
MonitorQueue and thread sleep are supported, which can ensure that the entire method block is executed in a single-threaded state
Original link:The hyperlink login is visible. |