---
title: "java double checked locking broken"
author: "wangyanlong0107"
date: "2018-09-15T01:56:25Z"
tags: []
categories: ["编程语言"]
slug: "java-double-checked-locking-broken"
draft: false
lastmod: "2018-09-15T01:58:43Z"
id: 2430702
url: "https://bigdragon.iteye.com/blog/2430702"
---

// 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;

}