Write to static field from instance method

帅比萌擦擦* 提交于 2019-12-22 08:44:59

问题


I have my code as below. I see

public MyClass{

    private static DataSource dataSource = null;

    private static DataSource getDataSource(){
        if (dataSource == null) {
            try {
                dataSource = // something.
            } catch (Exception e) {
                // some exception.
            }
        }

        return dataSource;
    }

    public List doSomething(){

        // ...

        if(dataSource == null){
            dataSource = getDataSource();
        }

        dataSource.getConnection();
        // ...

    }
}

I see following message in sonar anaylsis.

Dodgy - Write to static field from instance method

This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice.
findbugs:ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD Sep12 Reliability > Architecture

I see everything is okay in this implementation except that we are changing the static variable in doSomething method. How do we fix this ?


回答1:


Not sure how your static analysis tool works but -

try writing to your value via a static setter:

private synchronized static void setDataSource(DataSource ds) {
    dataSource = ds;
}

so that you can do

   if(dataSource == null){
        setDataSource(getDataSource());
   }



回答2:


You have to choose between two solutions , first one is in your Datasource class add getDatasource() method and synchronize the block where you instantiate your static field :

    private static DataSource getDataSource(){
     synchronize(DataSource.class){
            if (dataSource == null) {
                try {
                    dataSource = // something.
                } catch (Exception e) {
                    // some exception.
                }
            }
       }
        return dataSource;
      }

then you will just call this method from your doSomething() method

public void doSomething(){
//
DataSource dataSource=DataSource.getDataSource();
//
}

second solution is to instantiate your field at the class loading time using a static block or directly from the declaration.

static {
 dataSource = // something.
}


来源:https://stackoverflow.com/questions/24703755/write-to-static-field-from-instance-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!