Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the common undefined behaviours that Java Programmers should know about

Tags:

The same as this question but for java

Update Based on the comments and responses of a few people, Its clear that Java has very little undefined behaviour.

So I'd like to ask as well what behaviour is not obvious. Please when answering make the distinction between the two :)

like image 472
hhafez Avatar asked Dec 17 '08 22:12

hhafez


2 Answers

Anything to do with threads... :)

Also:

  • Overriding methods and expecting them to be used in the same way between versions
  • Assumptions about underlying platform (file separator, for instance)
  • Details of garbage collection/finalisation
  • Some details about class initialisation
  • Whether Integer.valueOf (and the like) return the same objects
  • Performance, latency and memory usage
like image 187
Tom Hawtin - tackline Avatar answered Oct 01 '22 03:10

Tom Hawtin - tackline


There is very, very little undefined behavior in Java, when compared to C/C++, it is a much more well-defined platform. The reason for this is that C/C++ compilers are meant to produce code for very different platforms and therefore were granted rather wide freedoms in order to prevent too stringent requirements that would force a compiler to produce suboptimal code for a given platform.

Java sacrificed some of that by defining almost every behavior in a very exact way and allowing only small degrees of freedom. This of course makes the platform somewhat easier to handle.

The main area where undefined behavior happens is the exact timing and scheduling of multiple threads (as Tom Hawtin already mentioned)..

There are several places where the behavior is not obvious, 'though, so it might look undefined, but isn't (the String comparison examples given by Oscar Reyes are a great example).

And a few places where the behavior is defined to be undefined (for example the order of elements in a HashMap is defined to be implementation dependent and needs not be constant).

like image 26
2 revs Avatar answered Oct 01 '22 03:10

2 revs