summaryrefslogtreecommitdiff
path: root/plugins/InspectionGadgets/test/com/siyeh/igtest/initialization/non_thread_safe_lazy_initialization/NonThreadSafeLazyInitialization.java
blob: 9b5987966ca685247d1aa76e19bbe9c5511f388c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.siyeh.igtest.threading;

public class NonThreadSafeLazyInitialization {
    private static Object foo;
    private Object instance;

    public Object getInstance() {
        if (instance == null) {
            instance = new Object();
        }
        return instance;
    }

    static
    {
        if (foo == null) {
            foo = new Object();
        }

    }

    {
        if (foo == null) {
            <warning descr="Lazy initialization of 'static' field 'foo' is not thread-safe">foo</warning> = new Object();
        }

    }

    public void instMethod() {
        if (foo == null) {
            <warning descr="Lazy initialization of 'static' field 'foo' is not thread-safe">foo</warning> = new Object();
        }
    }

    public static void staticMethod() {
        if (foo == null) {
            <warning descr="Lazy initialization of 'static' field 'foo' is not thread-safe">foo</warning> = new Object();
        }
    }

    public void lockedInstMethod() {
        synchronized (NonThreadSafeLazyInitialization.class) {
            if (foo == null) {
                foo = new Object();
            }
        }
    }

    private static String example = null;

    public  Object getInstance2() {
        if (foo == null) {
            while (true) {
                foo = "";
            }
        }
        return foo;
    }

    public Object getInstance3() {
        if (foo == null) <warning descr="Lazy initialization of 'static' field 'foo' is not thread-safe">foo</warning> = "";
        return foo;
    }
}