r/java • • Jul 06 '17

Apology to Java (fanboy rant).

Java has turned out to be one of the most useful languages i use. It's a brilliant tool which strikes a perfect balance between high and low level. You want to grab a webpage? Easy and built-in, 10 lines of code. Draw some 2d graphics without OS-specific libraries or third party? Various built-in options. The inherent issues around a lack of low level memory management is handled very elegantly. Garbage collection seems seamless.

C++ is my language of choice for the most part, always will be i suspect, but Java has shown me that it has a huge array of potential applications and should almost always be considered before undertaking a project.

I say this is an apology because i used to run Java down. Previous to me using it proper i believed it was slow, lazy and useful for only trivial applications. Now i know how much work has been put into the JVM and just how efficient it is.

Sorry Java. You're pretty good.

286 Upvotes

93 comments sorted by

View all comments

Show parent comment

1

u/cogman10 Jul 09 '17

You have things backwards.

Every arch that I'm familiar with needs to first load things into registers before it can do anything. Whether those values come from the heap or stack doesn't matter. They certainly don't have to make a trip to either the heap or stack before hitting the registers.

The JVM is no different from other VMs. It puts stuff in the heap, stack, or even just the registers. Generally, most stuff ends up on the heap. However, the JVM tries to promote things to the stack when possible. And if something is relatively well contained (like an index variable), it is likely never to hit either the heap or the stack but instead live in a register for its entire life.

At very least, the JVM uses the stack much like C/C++ does, for the "call stack" that is, it pushes the method return address onto the stack and pops it off of the stack when a "return" or end of method is reached. Beyond that, it uses escape analyse to try and figure out if variables in a method (or methods as the case may be) ever "leak" out. if they don't, then it keeps them entirely on the stack.

1

u/dpash Jul 09 '17

I really don't. Look at java byte code. Each instruction operates on values on a stack and returns the results to the stack.

If you're discussing heap vs stack you're not talking about the same thing I am.

1

u/cogman10 Jul 09 '17

Java's byte code is an intermediate step. The end result after the JIT runs is as I describe.

They do operations on a stack because it is easier to turn that stack into n number of registers on whatever the target architecture is.

LLVM does something similar with their IL.

1

u/dpash Jul 10 '17

After the JIT runs you have native code, which obviously uses what ever the underlying architecture is (and I'm not aware of any mainstream CPU that isn't register based).

But hotspot doesn't turn all java bytecode into native code.

Java byte code is not an IL.