当前位置:编程学习 > JAVA >>

使用findbugs经常碰到的问题Incorrect lazy initialization and update of static field

详细描述

This method contains an unsynchronized lazy initialization of a static field. After the field is set, the object stored into that location is further updated or accessed. The setting of the field is visible to other threads as soon as it is set. If the futher accesses in the method that set the field serve to initialize the object, then you have a very serious multithreading bug, unless something else prevents any other thread from accessing the stored object until it is fully initialized. 

Even if you feel confident that the method is never called by multiple threads, it might be better to not set the static field until the value you are setting it to is fully populated/initialized. 

有谁能解释下吗?一直对这个问题很模棱两可,不胜感谢 --------------------编程问答-------------------- --------------------编程问答-------------------- 多线程问题而已,你的方法引用了一个静态变量,估计是类静态变量,那么多线程调用这个方法时,你的变量就会面临线程安全的问题了 --------------------编程问答-------------------- 楼上能不能说的详细点,代码结构如下

class test{

public static oneclass oneclassname = null;

 public static test getinstance()
  {
    if(oneclassname  == null)
         {......}

  }


}


不明白有啥多线程的问题啊? --------------------编程问答--------------------
引用 2 楼 yuwenbao 的回复:
多线程问题而已,你的方法引用了一个静态变量,估计是类静态变量,那么多线程调用这个方法时,你的变量就会面临线程安全的问题了

正解

你把public static oneclass oneclassname = null; 
改成private --------------------编程问答-------------------- static 

已经不能更改了

没多大关系吧 --------------------编程问答--------------------
引用 5 楼 yetaodiao 的回复:
static

已经不能更改了

没多大关系吧

已经不能更改了??
final才不能被更改
public static 的,就是把自己暴露出去,谁爱用谁用吧~~ --------------------编程问答--------------------
引用 4 楼 imasmallbird 的回复:
引用 2 楼 yuwenbao 的回复:
多线程问题而已,你的方法引用了一个静态变量,估计是类静态变量,那么多线程调用这个方法时,你的变量就会面临线程安全的问题了

正解

你把public static oneclass oneclassname = null; 
改成private
 imasmallbird 说得对啊,不改不安全,不重要的项目就无所谓了,看给哪用了 --------------------编程问答-------------------- http://topic.csdn.net/u/20111013/16/6c4f8bc2-a4f4-4e2d-bfbf-9203f7aef810.html
参考里面火龙果的回答。不过,除非确实占据了太多资源,需要lazyload,否则,直接

static final XXX INSTANCE = new XXX();

或者

static final XXX INSTANCE;
static {
  INSTANCE = foo();
} --------------------编程问答-------------------- 如果高并发,参考火龙果C的答案
补充:Java ,  Java SE
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,