Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Final fields state when accessed from subclass

Tags:

java

I see a strange behaviour which seems shouldn't happen according to JMM. I have class B which extends class A, a final protected field in A which is initialized in A constructor accessed by class B in its constructor.

But, in very rare cases I get a NPE when accessed in B. Any ideas?

Part of the code:

class AsyncReplicationSourceGroup extends AbstractReplicationSourceGroup{

    public AsyncReplicationSourceGroup(DynamicSourceGroupConfigHolder groupConfig){
        super(groupConfig);
        createReplicationChannels();  
    }

    protected void createReplicationChannels(){
        //...
        specificLogger.finest("created channel");  // this is where the NPE is thrown from
        //...
    }
}

abstract class AbstractReplicationSourceGroup{

    protected final Logger specificLogger;

    public AbstractReplicationSourceGroup(DynamicSourceGroupConfigHolder groupConfigHolder){
        specificLogger = Logger.getLogger(Constants.LOGGER_REPLICATION_GROUP + "." + _groupConfigHolder.getConfig().getName());
        //...
    }

}
like image 444
Guy Korland Avatar asked Jun 18 '12 13:06

Guy Korland


1 Answers

It's impossible to tell for sure from the code posted alone, but if you are sure that the logger itself is null, (and you aren't mistakenly seeing a NPE from inside say, specificLogger.finest), then the most likely explanation is that Logger.getLogger is occasionally returning null for some reason.

I don't think the problem is threading because final fields assigned to in a constructor are guaranteed to be visible once the constructed object is visible as long as no references leak inside the constructor.

like image 147
Antimony Avatar answered Oct 06 '22 23:10

Antimony