1

Checking if reference is null every time it is used wouldn't be efficient enough... I suppose real implementation uses memory protection mechanisms to detect it. Can anyone explain in detail how does it actually work?

zduny
  • 2,481
  • 1
  • 27
  • 49
  • Possible duplicate of: http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java – BitNinja Apr 13 '14 at 20:45
  • I could say by reading JVM doc: they could use ifnull conditional to check if is null and throw the exception. But no idea. (i found this: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.11.9) – Marco Acierno Apr 13 '14 at 20:48

1 Answers1

1

I expect the implementation depends on the platform on which the Java Runtime Environment is running. On some underlying platforms, 0 is a legal address, so references would need to be checked each time; on others, memory protection mechanisms might be used, though ultimately those mechanisms still involve checking the reference.

Warren Dew
  • 8,790
  • 3
  • 30
  • 44
  • But handling an interrupt caused by memory protection is faster than checking the reference every time. – zduny Apr 13 '14 at 20:50
  • 1
    It only takes one machine instruction to check the reference, which is necessarily already in a processor register if you are about to use it. – Warren Dew Apr 13 '14 at 20:51
  • 1
    +1. Also remember that, in many cases, the compiler can determine statically whether a null is possible or not and discard unnecessary tests. (I don't know whether JAVAC does so, but I'm sure the JIT must.) – keshlam Apr 13 '14 at 21:13