`
leonzhx
  • 浏览: 796660 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论
阅读更多

1.  As is the case for most optimizations, the best advice for lazy initialization is “don’t do it unless you need to”. 

 

2.  If a field is accessed only on a fraction of the instances of a class and it is costly to initialize the field, then lazy initialization may be worthwhile. The only way to know for sure is to measure the performance of the class with and without lazy initialization.

 

3.  If you use lazy initialization to break an initialization circularity, use a synchronized accessor.


4.  If you need to use lazy initialization for performance on a static field, use the lazy initialization holder class idiom. This idiom (also known as the initialize-on-demand holder class idiom) exploits the guarantee that a class will not be initialized until it is used:

// Lazy initialization holder class idiom for static fields
private static class FieldHolder {
    static final FieldType field = computeFieldValue();
}
static FieldType getField() { return FieldHolder.field; }

 

When the getField method is invoked for the first time, it reads FieldHolder.field for the first time, causing the FieldHolder class to get initialized. A modern VM will synchronize field access only to initialize the class. Once the class is initialized, the VM will patch the code so that subsequent access to the field does not involve any testing or synchronization.

 

5.  If you need to use lazy initialization for performance on an instance field, use the double-check idiom. This idiom avoids the cost of locking when accessing the field after it has been initialized. The idea behind the idiom is to check the value of the field twice (hence the name double-check): once without locking, and then, if the field appears to be uninitialized, a second time with locking. Only if the second check indicates that the field is uninitialized does the call initialize the field. Because there is no locking if the field is already initialized, it is critical that the field be declared volatile:

 

// Double-check idiom for lazy initialization of instance fields
private volatile FieldType field;
FieldType getField() {
    FieldType result = field;
    if (result == null) { // First check (no locking)
        synchronized(this) {
            result = field;
            if (result == null) // Second check (with locking)
                field = result = computeFieldValue();
        }
    }
    return result;
}

 

What the local variable does is to ensure that field is read only once in the common case where it’s already initialized. While not strictly necessary, this may improve performance and is more elegant by the standards applied to low-level concurrent programming.

 

6.  Occasionally, you may need to lazily initialize an instance field that can tolerate repeated initialization. If you find yourself in this situation, you can use a variant of the double-check idiom that dispenses with the second check. It is, not surprisingly, known as the singlecheck idiom. Note that field is still declared volatile. If you don’t care whether every thread recalculates the value of a field, and the type of the field is a primitive other than long or double, then you may choose to remove the volatile modifier from the field declaration in the single-check idiom. This variant is known as the racy single-check idiom. It speeds up field access on some architectures, at the expense of additional initializations (up to one per thread that accesses the field). This is definitely an exotic technique, not for everyday use. It is, however, used by String instances to cache their hash codes.

 

分享到:
评论

相关推荐

    Effective Java 3rd edition(Effective Java第三版英文原版)附第二版

    Item 83: Use lazy initialization judiciously Item 84: Don’t depend on the thread scheduler 12 Serialization Item 85: Prefer alternatives to Java serialization Item 86: Implement Serializable with ...

    懒:Kule Lazy4 CSS框架

    懒:Kule Lazy4 CSS框架

    Effective C#

    **Item 13: Use Proper Initialization for Static Class Members** - **Importance:** Proper initialization ensures thread safety and avoids potential race conditions. - **Best Practice:** Initialize ...

    图片延迟加载,lazyload.js使用实例

    图片延迟加载(Lazy Load)是一种优化网页性能的技术,它通过只加载用户当前视口内的图片,而将其他未显示的图片推迟到用户滚动到相应位置时再加载,从而减少了页面初次加载的时间,提升了用户体验。在网页设计中,...

    C#使用Lazy延迟加载

    在.NET框架中,C#语言提供了许多特性来帮助开发者优化应用程序的性能,其中之一就是`Lazy<T>`类。这个类主要用于实现延迟加载(Lazy Loading),它允许我们推迟对象的初始化,直到真正需要使用该对象时才会执行初始...

    A History of Haskell - Being Lazy With Class

    3. **技术革新**:哈斯克尔引入了许多创新特性,如惰性求值(lazy evaluation)、类型推断(type inference)、高级数据类型(advanced data types)和模块系统(module system)等,这些特性极大地提高了程序的效率...

    版本:lazyload1.9.3..js

    lazyload1.9.3,图片延迟随滚动条显示。$(function() { $("img.lazyload").lazyload()});

    generator-lazy-demo:生成器懒人演示

    Generator Lazy Demo 跟着例子在3分钟内玩转Generator Lazy。 Useage 向导模式创建 在任意目录中执行yo lazy,然后一路NEXT即可。 在包含配置文件的项目中使用 命令: yo lazy cd build-with-config-exist yo lazy 在...

    lazyload使用案例及DEMO

    **图片懒加载技术详解与"lazyload"使用案例** 在现代网页设计中,为了提高页面加载速度和用户体验,"图片懒加载"(Lazy Loading)技术得到了广泛应用。它是一种优化策略,仅在用户滚动到图像所在区域时才加载图片,...

    react-lazyloading:React Lazy Loading - 使用 Intersection Observer API 延迟加载组件或任何内容

    React Lazy Loading - 很容易与 React 集成到 Lazyload 组件、图像等。它会监视元素并告诉您元素何时进入视口。 这样可以在视口中的组件和初始加载减少时执行任何操作。 实现“无限滚动”网站,在您滚动时加载和...

    懒惰对谷歌Chrome:trade_mark:「Lazy for Google Chrome:trade_mark:」-crx插件

    Lazy是一个帮助查看Salesforce部署期间发生的顶点运行测试的细节的工具。 这不是Salesforce.com产品。 在任何情况下,开发者均不对因使用本软件及其文档而引起的任何直接,间接,特殊,意外或间接损失(包括利润损失...

    Exopite-Lazy-Load-XT-WordPress-Plugin:Exopite Lazy Load XT使用Ressio Lazy Load XT jQuery插件延迟加载图像,视频和iframe

    Exopite-Lazy-Load-XT-WordPress-Plugin Exopite Lazy Load XT使用Ressio Lazy Load XT jQuery插件延迟加载图像,视频和iframe。 作者:乔·萨莱(Joe Szalai) 版本:20190521 插件URL: : 作者网址: : 许可...

    backportbot:向后移植将请求拉入释放分支的bot:robot:-Lazy source

    后台机器人 向后移植将请求拉入发布分支的bot 配置以下环境变量以进行部署: BACKPORT_GH_API = 'api_token_for_your_bot' BACKPORT_MAINTAINER = 'bot_listens_to_this_user' BACKPORT_BOT_GH_NAME = 'bot_github...

    lazyload-2.x.zip

    《jQuery LazyLoad 2.x API详解与应用实践》 在当今网页开发中,为了提高页面加载速度和用户体验,"懒加载"(Lazy Load)技术变得越来越重要。jQuery LazyLoad插件是一个广泛使用的解决方案,它允许图片、iframe等...

    lazy-line-painter:Lazy Line Painter-用于SVG路径动画的现代JS库

    根据快速入门说明,可以轻松完成Lazy Line Painter的设置。 但是,如果您更需要GUI,请确保使用 。 专为SVG路径动画开发的免费在线编辑器。 npm i lazy - line - painter < script src =" ...

    LazyBone:微框架

    LazyBone Micro框架 这是来自ribs.js示例的todoapp的演示。 它使用LazyRecord作为ORM,并通过Roller Router处理RESTful请求。 引导程序 安装洋葱: $ curl http://install.onionphp.org/ | bash $ onion bundle ...

    more effective c++

    #### Item 17:考虑使用LAZY EVALUATION(懒惰计算法) - **概念**:只有当结果真正被需要时才进行计算。 - **优势**:可以显著提高程序性能,尤其是在处理大量数据或复杂计算时。 #### Item 18:分期摊还期望的...

    RDF-Lazy:延迟键入对RDF数据的访问

    RDF :: Lazy-延迟键入对RDF数据的访问 概要 ### How to create a graph $g = RDF::Lazy->new( rdf => $data, # RDF::Trine::Model or ::Store (by reference) namespaces => { # namespace prefix, RDF::NS or RDF...

    System.Lazy 实例的延迟初始化值

    在.NET框架中,`System.Lazy<T>`是一个强大的工具,用于实现延迟初始化(Lazy Initialization)。延迟初始化是一种设计模式,它推迟对象的创建或资源的加载,直到第一次真正需要它们时。这种方式可以提高程序的性能...

Global site tag (gtag.js) - Google Analytics