zoukankan      html  css  js  c++  java
  • 使用dispatch_once实现单例

    转自http://www.jianshu.com/p/e03aa66a197f

    很多人实现单例会这样写: 

    @implementation XXClass
    
    + (id)sharedInstance {
        static XXClass *sharedInstance = nil;
        @synchronized(self) {
            if (!sharedInstance) {
                sharedInstance = [[self alloc] init];
            }
        }
        return sharedInstance;
    }

    相比之下: 

    @implementation XXClass
    
    + (id)sharedInstance {
        static XXClass *sharedInstance = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            if (!sharedInstance) {
                sharedInstance = [[self alloc] init];
            }
        });
        return sharedInstance;
    }

    使用dispatch_once可以简化代码并且彻底保证线程安全,开发者无需担心加锁或同步。此外,dispatch_once更高效,它没有使用重量级的同步机制,若是那样做的话,每次运行代码前都要获取锁。相反,此函数采用“原子访问”来查询标记,以判断其所对应的代码原来是否已经执行过。在64位Mac OS X上测试,后者的执行速度要比前者快一倍。

  • 相关阅读:
    strut2 国际化
    strut2 常量
    strut2 自定义类型转换器
    strut2基于XML配置方式对Action中的指定方法校验
    strut2 输入校验2
    strut2 输入校验
    strut2 模拟拦截器
    strut2 多个文件上传
    strut2 单个文件上传
    2015.01.01今年的第一天
  • 原文地址:https://www.cnblogs.com/liuting-1204/p/6389205.html
Copyright © 2011-2022 走看看