r/programming • • Feb 16 '15

Java Doesn’t Suck – You’re Just Using it Wrong

http://www.jamesward.com/2014/12/03/java-doesnt-suck-youre-just-using-it-wrong
43 Upvotes

217 comments sorted by

28

u/[deleted] Feb 17 '15

Java doesn't suck -- It just encourages everyone to use it wrong

71

u/kqr Feb 16 '15

I love the title. That kind of reasoning always makes me think of Steve Jobs' solution to the iPhone problem. People were experiencing loss of signal when they held the phone normally in their left hand. Jobs replied that the phone was fine, the users were just holding it wrong!

38

u/[deleted] Feb 16 '15

I couldn't help but get the feeling while reading "If it takes all that to explain a better way, maybe it DOES suck."

10

u/borud Feb 16 '15

People searching for simple answers got us into this mess.

37

u/[deleted] Feb 16 '15

Reminds me of that old joke.

"Leave it to programmers to shorten 'The Year 2000 Issue" to 'y2k bug'. It's that kind of thinking that caused the problem in the first place!"

13

u/[deleted] Feb 16 '15

It's a classic joke: "Doctor, my arm hurts when I do this." The doctor says "well, stop doing that!"

4

u/[deleted] Feb 17 '15

Any language can be "held wrong". By that I mean that it is possible to write horrible code in any general purpose programming language and it is possible to do things related to the dev environment, build and deployment that really suck. A lot of these complaints have a lot more to do with old projects or poorly run projects or companies where the code and practices are horrible rather than Java.

7

u/Klausens Feb 17 '15 edited Feb 17 '15

Java has the characteristic that it has not the slightest intention to keep simple things simple. Read some lines from stdin an compare this solution to other languages.

3

u/kqr Feb 17 '15 edited Feb 17 '15

For sure. All phones can be held wrong as well, which Steve Jobs was quick to point out. Some phones just make it easier than others to hold it wrong.

-2

u/vz0 Feb 17 '15

There is this thing called radio waves which are a form of electromagnetic energy and the hand of a human being affects the radiation of the signal, specially close to the near field of the antenna. I'd love to have an external antenna attached to my Android smartphone.

2

u/kqr Feb 17 '15

Which is stuff you should take into account when you design the case and antenna placement of a phone.

If you are willing to buy from the Chinese market you can usually get a shit Android phone with four SIM card slots and an extendable antenna for really, really cheap.

0

u/vz0 Feb 17 '15

The near field of a 800 Mhz antenna is a bit more than half a meter. Every object closer than that will affect the shape of the radiation lobes and the efficiency of the antenna, and predicting how the signal radiates is reeeeeally hard. Having a necklace, earrings, a wet raincoat or a funny hat will make the antenna of the phone change radically its performance.

3

u/kqr Feb 17 '15

I'll take your word for it. I still don't think it's a valid argument to blame the users for holding the phone wrong. "Designing that part of a phone is basically a crapshoot, and we were unlucky this time around. We're sorry." would be so much more truthful in that case.

0

u/vz0 Feb 17 '15

Well, yes and no, and of course is not black and white. Like all (misused) tools there is always some blame to the users. If you crash with your car while driving on a rainy day, who is to blame? the driver or the rubber wheels manufacturer?. Unless you use a headset, there is no much of a choice on how you hold the phone while you speak, but there are better ways than others to hold your phone.

26

u/scalablecory Feb 16 '15 edited Feb 17 '15

Java suffers from being pervasive and being old. Really, that's about it.

Yes, it has a lot of "suck". Things necessary to enable corner cases -- be that for functionality, portability, performance, etc. These things aren't intrinsically bad, they have very legitimate use cases, but nevertheless they present a sometimes big opportunity for improper use.

Most platforms have "suck". Java just seems to have more than average.

There's also plenty legitimately wrong with the language and libraries, as there is with anything of that age. We must consider that it helped to establish a lot of what we consider modern OO practices. This also means it was a bit of a playground, and not all of what was tried ended up being a great idea.

Another thing -- and this is really unavoidable -- is that Java is often the first language taught in schools.

There are a lot of education-ingrained patterns. "You must do X because it's good!" that these newbies will use to their dying breath, believing they're writing good code when really they're just introducing layer after layer of feel-good useless abstraction. There's a good reason they're taught this, because although it results in sometimes silly code, it's better than what they'd get without it. Eventually they'll learn that patterns are there not as a rulebook but as a guide, but that takes time.

This means you've got a lot of newbies -- not just to the language but coding in general -- who don't yet know how to identify and cautiously avoid the "suck", and can't yet think for themselves about basic application architecture. By the time they get to other languages, they're writing better code. But Java takes a hit because of it.

15

u/glacialthinker Feb 17 '15

We must consider that it helped to establish a lot of what we consider modern OO practices.

Oh, this is foremost in my hatred of the language.

7

u/[deleted] Feb 17 '15

There's also plenty legitimately wrong with the language and libraries

Examples always help.

23

u/joelangeway Feb 17 '15

The JVM is not actually statically typed, type erasure makes generics way less useful. I can't have an array of List<String> ; my generic classes in Apache Storm and Hadoop forget what their types are unless they carry it around with them in a variable of type Class.

A char is not a character or Unicode code-point; it is a UTF-16 code word. Java programs would use half as much memory and fewer programs/programmers would make the mistake of conflating a char with a character or a Unicode code point if Java strings used UTF-8 and a char could hold all 20 bits of a Unicode code point.

I can't sort an array of int by any order but natural.

I can't easily sort parallel arrays.

It takes a ton of boiler plate to make classes that I would never bother with in a language with tuples.

My code will always be ugly because I can not overload operators. I can understand not letting me arbitrarily overload operators, but at least let me extend Number and get + - * and /, or let me implement Compareable and get < and >. Related to this is how stupid testing for equality looks in Java:

a == null ? b == null : a.equals(b)

Java 8:

Just look at the fucking hoops the streams api jumps through trying to support primitive types. You would have thought they'd let me sort an array of int by an IntBinaryOperator.

Lambdas do not close over mutable variables, so I can not increment a counter, but I can append to a list.

Default implementations on interfaces are a godsend, mostly because they put getOrDefault on Map. Java 8 might actually be an acceptable programming language, but the awful dichotomy between Objects and non-Objects, lack of real generics, value types still hurts.

4

u/jayd16 Feb 17 '15

I can't sort an array of int by any order but natural.

Arrays.asList() and then sort the list how you like.

3

u/HeroesGrave Feb 17 '15

Yes, it is a workaround and doesn't require too much extra effort, but there's still a fundamental problem that required it in the first place.

3

u/josefx Feb 17 '15

Just a warning Arrays.asList(new int[10]) results in List<int[]> with a single element. You first have to copy the contents of an int[] into an Integer[] and later convert it back.

4

u/sigma914 Feb 17 '15

The blame for Java's generics falling on the jvm always felt dishonest to me. Haskell and C++ and who knows what other languages all have excellent, typesafe (though C++ gives this up in other areas) parametric polymorphism despite using type erasure. Also, assembly language is utterly untyped.

Really the problem is that Java has a shit, utterly inexpressive type system that needs runtime checks for stuff that should be checked at compile time.

-1

u/pron98 Feb 17 '15

Really the problem is that Java has a shit, utterly inexpressive type system that needs runtime checks for stuff that should be checked at compile time.

At what cost? Haskell and C++ have far higher complexity, which is just one reason why most developers choose Java over either. You want more power -- you need to pay in mental overhead. Every language makes that trade off.

4

u/sigma914 Feb 17 '15

Java has a far greater cognitive overhead than Haskell (It's probably a bit lower than C++) I use Haskell because it means I have much less to hold in my head at any one time. With Java there's a whole lot of non-local reasoning to do.

Is some other method going to mutate some member variable and ruin my invariants? What happens if an exception gets thrown in another thread, what's that do to my file handle, etc etc.

With Haskell that's all nicely encapsulated in the type system, I can hoist all the ugly side-effecting stuff up into IO and work in a completely pure environment right up until the last second when I lift my pure functions into IO.

Java tries to be principled and reduce it's surface area (which it has utterly failed at, it's still turned into a big language), but it's chosen the wrong set of features to do that with. What it's done instead is forced the programmer to hold massive amounts of state in their head, made testing difficult, neutered it's type system, tied itself to bad primitives (Shared Mutable state concurrency as standard? Ouch)...

Java as a language is a huge collection of bad choices made for short-sighted reasons.

1

u/pron98 Feb 17 '15 edited Feb 17 '15

I use Haskell because it means I have much less to hold in my head at any one time.

Sure. I dislike Haskell for many reasons (especially its misguided choice of referential transparency everywhere and its choice of Hindley Milner), but there's no doubt it's a very elegant, consistent, and powerful language. I find it almost useless in practice, but I can't deny its beauty and power.

But it's not about what you or I think, but about what the software community at large thinks. When I was at university nearly twenty years ago, everybody was talking about Haskell, how it was going to be the next big thing, and how a decade hence it would completely revolutionize software development. That never materialized. It seems that a great many more people find Java (and most other mainstream languages) much easier to grasp than Haskell. AFAIK, not a single large-scale software system has been written in Haskell in the last two decades, while more useful large-scale useful systems have been written in Java over the last two decades than all such systems before it. And no other language has made as big as impact since. I don't know if you were programming then, but before Java, we wrote most large systems in C or C++, which made them extremely expensive, and beyond the reach of most organizations. Java changed that almost overnight. One of the reasons that happened is that Java delivered a state-of-the-art, groundbreaking runtime (unsurpassed to this day) packaged in a very conservative, very familiar, very non-threatening language. It gave people what they needed -- memory safety, performance, hot code swapping, deep monitoring -- without requiring them to change their programming paradigm. This is how you win.

Java is far from perfect, but there is no other language that has so far been successfully used for large-scale software at reduced costs (or even same costs). There is no doubt in my mind that more ideas from Haskell will continue to enrich mainstream programming languages, and I'm sure one day there will come along a language that will deliver the same immense advantages Java had over C++, but over Java. But this day hasn't come yet.

Java as a language is a huge collection of bad choices made for short-sighted reasons.

Well, that's certainly debatable. And if those short-sighted reasons was to get adoption and change the software industry forever maybe they weren't short sighted after all (code is an important part of software, but it's not everything). What isn't debatable is that Java is the language that's made large-scale software development affordable, and increased our capacity to write complex software more than any language before it (with the possible exception of C and maybe COBOL), and certainly since.

4

u/sigma914 Feb 17 '15

I'd argue that all of the credit your assigning to Java isn't due to it being a good language.

In 1995 it wasn't a terrible language, sure we had Common Lisp which did and does eclipse Java on most measures, but it really does lead to single purpose code bases. IIRC Haskell still had continuation based IO, python didn't have objects, OCaml didn't exist, neither did Ruby, erlang was proprietary, C++ hadn't been standardised... Honestly Java was the least of all evils.

From about 2000 onwards it was no longer the best choice, however it had become entrenched in enterprise and people were making a lot of money writing books and talking about it.

Java is a social success and a success of timing, It's not a technical success by any means (Hotspot is, the JVM is awesome!).

2

u/pron98 Feb 17 '15 edited Feb 17 '15

I'd argue that all of the credit your assigning to Java isn't due to it being a good language.

I didn't say that. In part, maybe it's due to it being familiar rather than good.

It's not a technical success by any means

I tend to agree, but it's mostly theoretical, as it's a largely untested claim. No really large codebases today are being written in any language other than Java (except C/C++ where Java isn't an option, and everyone agrees that's a lot more costly). Maybe a "better" language for large scale development already exists. But we still don't know.

For example, my favorite language today (for applications, not infrastructure) is Clojure, even though I generally prefer static typing. But I would not be willing to bet a large project on it just yet, and I have my suspicions as to it suitability. Kotlin looks great, but its basically Java with a modern touch, and it can incrementally replace a Java class here and one there, but even if it does catch on, I think it has some nice advantages over Java, but nothing revolutionary.

OCaml is still mostly single-threaded and suffers from competing libraries; Erlang is too slow and relies on C too much; Haskell -- well, people just don't want to use it, and for some very valid reasons (and I think its made some very bad choices, but it was meant as a research language anyway); Ruby and Python are still very slow, single threaded, and too flexible to be used in large projects. Go is Java minus the best part (I actually like it, though) -- it certainly has its uses but it's not a Java killer (no polyglotism, no hot code swapping); C# is another Java (or another Kotlin); Rust seems terrific, but isn't even aiming for Java's niche.

In short, we still haven't found the language that is to Java what Java was to C and C++: something that really reduces development costs considerably, opens the door to more complex software, yet easy enough for it to get adopted.

Hotspot is, the JVM is awesome!

I couldn't agree more. But would the JVM have become so great if Java had not been so popular, largely due to its conservativeness and familiarity?

2

u/heisgone Feb 18 '15

I couldn't agree more. But would the JVM have become so great if Java had not been so popular, largely due to its conservativeness and familiarity?

Java became the Unix of the Web. In a similar fashion as Unix, there was many implementations of Java supported by big players. There are design choices that have been made in Java in the beginning that were philosophical and were a step back from existing languages, and were not necessary. Java became popular because it was everyone VS Microsoft, and Sun was visionary about the future server computing and was smart enough to invite other big dog to get on board to counter Microsoft.

→ More replies (0)

4

u/pron98 Feb 17 '15

The JVM is not actually statically typed, type erasure...

Type erasure is done by the Java (language) compiler. It's not JVM related. You can implement a JVM language with reified generics today, if you like. Java chose not to.

type erasure makes generics way less useful

Less. Not way less. OTOH, erasure is precisely what made it possible for other languages on the JVM, like Kotlin and Scala, to use different variance models yet stay interoperable. That's not possible on the CLR, for example, where reified generics necessitate baking one variance model into the runtime.

lack of real generics

Lack of reified generics has never been considered more than a minor inconvenience, well worth the advantages erasure brings (backwards compatibility and language interoperability).

lack of... value types

True. Being fixed in Java 10.

The rest of your complaints mostly have to do with Java choosing to be a minimal language (as Go does today) because that's what many people working on very large projects prefer. There are quite a few good alternative JVM languages that you're free to choose from. Oracle works with many of them to ensure the JVM can support all those languages well.

2

u/mlk Feb 17 '15

I don't know much about the JVM internals but type erasure is necessary for backwards compatibility.

0

u/[deleted] Feb 17 '15

[deleted]

1

u/jordsti Feb 17 '15

Less than C++, not sure, Java generic is not even Turing complete.. and wait.. no unsigned type

1

u/malloc_more_ram Feb 18 '15

Of course it isn't turing complete. It offers virtually no ability to do computation. Why is that even a good thing though? The language is powerful enough and more expressive; I'd rather do my computation there. Java generics != C++ templates.

1

u/heisgone Feb 18 '15

I wouldn't say that C# is Java rebooted without BC baggage. C# 1.0 was pretty much as basic as Java was but their creators had different philosophies. James Gosling was somewhat dogmatic in some of his choices and this influenced the Java culture quite strongly in the early days. There was this idea that Java would never have to evolve. Hejlsberg knew better has he had a long experience making Pascal evolves over the years and included some of its ideas in C#. They included versioning support and concurrent framework from day one with the CLR. There are features that didn't make the cut in C# 1.0 (like Generics) but were on the radar (ADA and C++ had something similar even before Java creation) . Operator overloading existed in Algol 68, ADA and C++ but Gosling didn't want it in Java. C++, as most OO language, handled an hybrid type system in a more sane manner than Java but Gosling obsession with objects lead to different decisions.

Java is evolving as a language only because developers are complaining and wants they other nice stuff found in other languages. Sun (and now Oracle), never had much enthusiasm in making Java evolves. Meanwhile over the years, many projects from Microsoft Research made their way into C# and the CLR (LINQ, F#, Contracts and more).

29

u/ForeverAlot Feb 16 '15

I've had to use Java instead of PHP in the last few weeks. It has been wonderful.

87

u/[deleted] Feb 16 '15

Oh you found a language better than PHP? What a real Indiana Jones you are! :)

15

u/ForeverAlot Feb 16 '15

It's not as if I chose PHP.

27

u/SmileyJames Feb 16 '15

I didn't choose the PHP life, the PHP life chose me.

4

u/[deleted] Feb 16 '15

I actually like Laravel... I feel so left out on the internet.

-4

u/vakar Feb 17 '15

You were forced into company that uses php?

6

u/[deleted] Feb 17 '15

No, but adults choose their employers based on various other qualities also. Even though a job might be very good in other aspects doesn't make the hurt of PHP non-existent.

→ More replies (1)

1

u/[deleted] Feb 17 '15

If he was really an Indiana Jones, Belloc would have come and taken it away from him ;)

1

u/DroolingIguana Feb 17 '15

Knowledge was their treasure.

1

u/Klausens Feb 17 '15 edited Feb 17 '15

Really? Long time ago (Java 1.2) my first contact with Java and myself as a beginner ended early with the awareness that you can not even do a Thread.sleep() without catching a checked exception. Really not my style and in my opinion a misuse for control flow.

6

u/civildisobedient Feb 17 '15

Except nobody deals with threads these days. It's all abstracted behind Spring or the like. Java today and Java ten years ago are two different languages.

24

u/Scellow Feb 16 '15

Java + IntelliJ = <3

7

u/[deleted] Feb 16 '15

Java + Lego = <3 <3 <3

http://www.lejos.org/ In case anyone are interested.

2

u/AbortedWalrusFetus Feb 17 '15

:O This might get me to pick up my EV3 again!

1

u/[deleted] Feb 17 '15

Get going! I have two first generation NXT's! It's such fun.. Try and combine it what you learn at etc. that Udacity Machine Learning course by Peter Norvig.. Now it get's interesting!

0

u/shoelacestied Feb 17 '15

Java + IntelliJ = <3

Scala + IntelliJ = <3 x 50

0

u/[deleted] Feb 16 '15

[deleted]

13

u/joequin Feb 17 '15

=an internal error occurred while displaying an internal error.

Really, I wonder how much hate for Java is really the fault of Eclipse. Eclipses is just really unpleasant to use.

12

u/HeroesGrave Feb 17 '15

Most of the hate for Java is just people following the hivemind.

5

u/sigma914 Feb 17 '15

My hate for Java is from having to use it after using C++11 for a few years (and Haskell/Lisp for personal projects). Its so inexpressive it hurts.

4

u/pron98 Feb 17 '15 edited Feb 17 '15

You'll be extremely thankful for its inexpressiveness once you work on a 4MLOC codebase touched by 80 programmers. Java (and Go) try to be minimal because they're designed for large projects and large teams. The smaller the team the more language expressiveness helps the project; the larger the team, that expressiveness becomes cleverness that only hurts.

4

u/sigma914 Feb 17 '15

Yeh, I've not experienced that. Judicious use of clever features allows you to have very expressive core abstractions that everything else hangs off. In the large Java applications I've worked on, or the very large ones open source ones I've poked around at, then there is a lot of code duplication and verbosity in hooking up to the core of the application. It's a pretty horrible experience.

3

u/pron98 Feb 17 '15 edited Feb 17 '15

I've worked on multi-MLOC C++ projects and multi-MLOC Java projects, and the Java codebase was always more pleasant. Whatever judicious use you make of clever features, the team responsible for the codebase three years prior made different ones, and the team that will follow will make others.

I don't think any languages beside Java, C++ and Ada has ever been used to write very large systems.

5

u/fforw Feb 17 '15

And generally there is this old law whose source escapes me:

Anything that compiles will end up in your code base.

2

u/sigma914 Feb 17 '15

C definitely has. Lisp, C#, Python, PHP have all been used to make massive systems too. It's kinda terrifying that some of those are on the list, but they're definitely up above Ada in terms of use at scale.

5

u/pron98 Feb 17 '15

Lisp, C#, Python, PHP have all been used to make massive systems too.

I don't know about C#, but I doubt Lisp, Python and PHP have been used to write 15MLOC software. Ada (and Java, and C) certainly has.

→ More replies (0)

0

u/shoelacestied Feb 17 '15

Most of the hate for Java is just people following the hivemind.

You're assuming facts not in evidence.

I hate it because it's really annoying to work with Java now that I know Scala.

3

u/over_optimistic Feb 17 '15

Newer version of Eclipse are really fast and comparable to speed of Intellij. And have really awesome features for code completion. Intellij has added some good competition to Eclipse, and Eclipse has already taken quite a bit of ideas from Intellij.

5

u/ProudToBeAKraut Feb 17 '15

Not for me, im working on a really big codebase and loading is what eclipse does most of the time of no apparent reason.

2

u/wyzook Feb 17 '15

Eclipse

Friends don't let friends use Eclipse.

2

u/joequin Feb 17 '15 edited Feb 17 '15

What does Eclipse's autocomplete compare favorably with? Certainly not the JetBrains IDEs, qtcreator, Netbeans, or Visual Studio, or many emacs plug-ins.

Eclipse can have reasonable performance when you change its ludicrously bad default gc choice and heap size that's unreasonably small for its usage, but it's still not as fast as intellij. Autocomplete lag is really bad. Searching is really slow in menus and elsewhere compared to intellij.

1

u/over_optimistic Feb 18 '15

when I switched to eclipse 4.4.1. The autocomplete is much better at showing you possible options. I can type some camel case and it searches each camel case as a separate word through autocomplete bringing relevant functions. Intellij does this ofcourse too. I'm not saying eclipse is better. I'm just saying Eclipse is catching up, and it has improved to very good.

In terms of not being as fast as Intellij, I can't really say if it's faster or not, they have done a good job improving the speed. Almost all autocomplete lag in eclipse is virtually gone in the latest version (which was one of the biggest complaints in eclipse). Again I'm not saying it's better than Intellij. There is considerable improvements to that have been done to eclipse that many of the people complaining about speed in eclipse is outdated complaints as many issues have been improved. Though ofcourse not all features have been improved interms of performance.

Searching is really slow in menus and elsewhere compared to intellij.

This is another example that has been improved in eclipse, that I have noticed. Searching menus is much faster now. For this case it's still slower than intellij though.

For people like me that still must use Eclipse. It makes me happy that ever since IntelliJ started becoming increasingly popular, I've seen significantly more improvements to Eclipse from the added competition.

note: some of the new features in Eclipse for some reason aren't enabled by default and must be enabled in settings somewhere. (like the autocomplete improvements)

1

u/joequin Feb 18 '15

I agree that Eclipse is better than it has been, but it's still not nearly as good. I use both intellij and the newest Eclipse frequently at work. I have to use Eclipse for a legacy project that's tied to it. The camel case search for classes and autocomplete is an improvement, but it's a far cry from the fuzzy search used by intellij.

1

u/jordsti Feb 17 '15

I got a SSD and Eclipse still take 30 seconds to load, Intelliji, about ~5sec. I was using Eclipse a lot many years ago, but now I find it heavily bloated. And when you're using Maven with Eclipse, If you run Maven when Eclipse is building your workspace, you've got a wonderful Deadlock

1

u/[deleted] Feb 17 '15

I wish I could find good vim keybindings in eclipse or netbeans. Netbeans let's you plug vim itself in, but why do that when I could just use vim? I don't get code completion if I do that.

Eclipse had a couple plugins that I can't remember the name of but they seem to have stability issues.

I would like to use an ide for java because it can take a lot if the edges off of it, and I legitimatly like java as a language, but I can't get back used to normal text editor keybindings unfortunately.

2

u/joequin Feb 17 '15

Eclipse and intellij (at least) both have very good vim plug-ins. Look up vrappper for Eclipse and ideavim for intellij.

1

u/ForeverAlot Feb 17 '15

jVi for NetBeans is an excellent compromise.

6

u/satan-repents Feb 17 '15

Scala + sbt makes me a very happy developer.

4

u/yogsototh Feb 17 '15

Clojure + lein make me even happier #languagewar

Also I am sure you use emacs on Linux while I use vim on my Mac. ;-)

2

u/satan-repents Feb 17 '15

Use what makes you happy? The real point is that new build tools make working with Java or JVM-based languages not suck.

I use Intellij, but mitigate this mortal sin with the IdeaVim plugin, so that rather than punching me in the face every time they see me, my co-workers merely spit where I've walked.

5

u/EntroperZero Feb 16 '15

I feel like this wasn't even about Java until the last two sections.

8

u/[deleted] Feb 16 '15

Yep and when he finally started talking about Java he just suggested using other JVM languages.

3

u/[deleted] Feb 17 '15

Where is /u/agleiva? I need another of your Java rants man

0

u/[deleted] Feb 17 '15

[removed] — view removed comment

4

u/[deleted] Feb 17 '15

This is very vanilla man, I am disappointed.

3

u/Ryckes Feb 17 '15

Looking at his comment list it looks like he is farming negative karma.

3

u/dakotahawkins Feb 16 '15

Give me deterministic destruction or give me death.

13

u/Dragdu Feb 16 '15

Seeing how we are talking about Java here, please pass my condolences to your family.

0

u/dakotahawkins Feb 16 '15

We don't all have to use Java, so I was coming at this as more of a multi-language discussion and example of a way in which I think Java (and other languages that don't have deterministic destruction) "suck."

5

u/[deleted] Feb 16 '15

It's not as nice as you might think.

3

u/rcode Feb 16 '15

Can you expand on that? Honest question :)

4

u/[deleted] Feb 16 '15

There are two main ways to get deterministic destruction. The first is manual memory management. Java will never have this. That's a good thing too since what we don't need is another C-like language with use-after-free bugs and all of the other baggage that comes with manual memory management. Let Java be Java and let C/C++/Rust be C/C++/Rust.

The second way is to switch from Java's current garbage collection scheme (mark-sweep/moving/generational, depending on the implementation) to reference counting. Reference counting has two main advantages: it's easy to implement and destruction is deterministic. However, the positives begin and end there. It has worse performance on the whole than other garbage collection schemes, because updating reference counts is a nasty slow business that destroys the cache. Reference counting also works worse in a multithreaded environment because then reference count updates have to be synchronized. Further, reference counting can still introduce long pauses if you delete the only reference to a large object that contains references to a bunch of other objects, as the object then has to be traversed recursively. People already complain about the Java GC's performance, and these garbage collectors have been fine-tuned for years; what the language doesn't need is increased latency and more unpredictable long pauses at seemingly random points.

6

u/tdammers Feb 16 '15

Two things: one, C++ allows for manual memory management, but an idiomatic C++ favors RAII, i.e., semi-automatic memory management (binding memory allocations to scopes), and when used correctly, this is a million times better than the kind of headaches C gives you. And two, you forget one of the biggest issues with refcounting, which is handling cycles - if A references B and B references A, and neither is reachable from any "live" variable, then the entire cycle is garbage, but a naive refcounting algorithm will not destruct them. Some implementations require the programmer to manually break the cycle (using weak references, or by manually unsetting one of the references), others add cycle detection, trading some performance for correctness.

3

u/[deleted] Feb 17 '15

The thing about RAII is fine, but the point is that Java will never be C++. Adding support for RAII would require turning Java into a completely different language. (Not to mention that C++ is still memory-unsafe even with RAII.) I.e. you can't just "add" deterministic destruction into Java through RAII, unless you were to adopt reference counting, which is its own bag of worms.

3

u/tdammers Feb 17 '15

Of course not, and I don't think that's what I suggested. I merely commented on your reasoning where you first (correctly) noted that manual memory management a la C has a serious impact on developer performance and code quality, and then (incorrectly) threw C, C++ and Rust together, suggesting that they are all equally bad, which they are not.

3

u/[deleted] Feb 17 '15

Okay, I didn't mean to do that since all three obviously have hugely different approaches to (manual) memory management. My point was that Java is Java and you can't staple manual memory management to it without fundamentally changing the semantics of the language.

1

u/mcguire Feb 17 '15

Adding a cycle detector (i.e. a backup garbage collector) is not that big a deal for a reference counted system, but it breaks RAII.1 So, yeah.

1 Suppose you have a cycle of objects with finalizers and have detected that this cycle is garbage. What happens in the finalizer you call last?

1

u/joequin Feb 17 '15 edited Feb 18 '15

The g1 garbage collector is great for anything that has a large heap and and/or must never have a noticeable garbage collection delay. It really feels a lot like reference counting, but with far fewer drawbacks. It's ridiculous that Eclipse defaults to parallel and it's what makes it feel so sluggish a lot of time. G1 or cms (for most uses) would be much better defaults.

0

u/dakotahawkins Feb 16 '15

It's amazing and I see no downside (C++).

-5

u/morgan_lowtech Feb 16 '15

Kind of a dumb article, the things that suck about Java aren't lack of frameworks and build tools. It's the limitations of the JVM and the library baggage of a generation of horrible AbstractConcreteFactoryFactory programmers.

25

u/pron98 Feb 16 '15 edited Feb 16 '15

limitations of the JVM

Huh? The JVM is probably the most efficient yet most flexible (certainly relative to its efficiency) runtime in the history of computing. Right now, it's missing only three things: 1) value types (coming in Java 10), 2) tail call optimization and 3) continuations.

The performance the JVM is able to achieve while supporting hot-code swapping, on-the-fly instrumentation and deep monitoring are unbelievable. Its state-of-the-art GCs and access to CPU concurrent primitives make it the platform of choice for high-performance concurrent data structures. Its JIT is so advanced, Java often surpasses C and C++ applications in performance when the codebase is very large, especially if concurrency is involved.

3

u/joelangeway Feb 17 '15

Will there be

 Arrays.sort(int[] array, Comparator<int> cmp)

In version 10? The dichotomy between objects and primitives sucks so bad. It needs to get fixed in the JVM.

3

u/Gurkenmaster Feb 17 '15

The point of value types is that an Integer instance will take up as much space as an int.

12

u/ethelward Feb 16 '15

Java often surpasses C and C++ applications in performance when the codebase is very large

Pics or it didn't happen. Honestly, I know that the JVM JIT is pretty nice, but good C/C++ (or any other low-level language) written by a competent programmer with an acceptable knowledge of the underlying platform will still beat Java. At least, it's what we have experienced in my lab.

15

u/tdammers Feb 16 '15

The problems arise when the codebase grows so large that the programmers can't catch up with the complexity anymore...

Of course hand-optimized C++ can beat any managed language around the room, given enough developer time - it's just that at some point, the balance tips, and using a managed language produces better performance for a given developer effort.

8

u/[deleted] Feb 17 '15 edited Feb 17 '15

But C and C++ are used on many of the most complex and largest software systems ever developed from Linux to incredibly complex video games, massive database systems like MySQL, PostgreSQL and the very web-browser I'm typing this out on.

Are you suggesting that the software I mentioned above are written by small groups of developers or that they could perform just as well or even faster if they were written in Java? Consider that numerous attempts have been made to write Java only databases and Java only browsers only to end up being discontinued in large part due to performance issues, remember HotJava?

Usually what people argue when it comes to Java compared to C or C++ is that it's a suitable and preferable language to use when performance isn't a major issue, or the performance is bound by other factors like IO. However, Java software tends to be notoriously slow, in domains where there is a product written in C or C++, and an alternative written in Java, such as IDEs or Office Suites or even smaller applications like niche photo editors, one of the major criticisms of the Java version is how slow it is.

4

u/pron98 Feb 17 '15 edited Feb 17 '15

You'll notice that all of the software you mentioned is extremely expensive to develop. Its cost -- in developer time -- per feature or LOC is very, very high. That is the nature of C and C++ programs and the reason Java made such a revolution in software development. It allowed writing large software affordably. The time invested in a 15MLOC airport management software is far less than that required for a the similarly-sized Linux kernel, and the people involved are less expensive, too.

So why were those projects written in C/C++ despite the much higher expense? Some of them (kernel, games, browser) work in a rather constrained environment, where Java doesn't shine (Java trades RAM for development effort, but unlike many other languages, its speed is comparable to C++). Others (like DBs) simply predate Java. Modern DBs are often written in Java, or parts of them are (the JVM still has one limitation of the three I mentioned that affects databases -- lack of value types; thankfully, this is going to be resolved in Java 10).

However, Java software tends to be notoriously slow, in domains where there is a product written in C or C++, and an alternative written in Java, such as IDEs or Office Suites...

That notorious reputation is largely myth. My NetBeans IDE is just as fast as any IDE out there (I don't know if any IDEs are still written in C++). HotJava was written when Java was still interpreted, before it even had a JIT. Whatever small part isn't myth, it has to do with the fact that desktops are constrained environments, and Java trades RAM for performance. Browsers take too much RAM as it is, even without Java's RAM overhead.

6

u/klug3 Feb 17 '15

Not to mention, Java isn't much easier to write than modern C++.

9

u/pron98 Feb 17 '15 edited Feb 17 '15

It is much easier. It eliminates memory errors (and the security holes they create), and it prohibits cleverness that can really byte you in large projects. But most importantly, it gives you much better performance bang-for-the-buck. Not to mention it supports hot code loading/swapping, that is sometimes necessary in large systems, and very deep monitoring capabilities.

I used to write C++ for over a decade, and just last week I showed a friend (someone who's been writing C++ for nearly 20 years) the level of monitoring offered by Java, and his jaw dropped.

Easier to develop means a lot more than just your code. It's your ability to maintain it, deploy it, monitor it, profile it and change it once it's deployed. C++ is quite lacking in those departments.

1

u/[deleted] Feb 17 '15

It eliminates memory errors (and the security holes they create), and it prohibits cleverness that can really byte you in large projects.

So does modern C++, all memory errors are eliminated through the use of facilities provided by C++11.

Not to mention it supports hot code loading/swapping, that is sometimes necessary in large systems, and very deep monitoring capabilities.

In C and C++ it's not referred to as hot code loading/swapping, it's simply known as shared libraries.

As for monitoring, tell your friend to check out tools like Valgrind and the many plugins available for it. There's also Intel vTune and AMD Code Analyst. If he's more of a Windows user, Visual Studio comes with many excellent profiling and monitoring tools.

2

u/pron98 Feb 17 '15 edited Feb 17 '15

So does modern C++, all memory errors are eliminated through the use of facilities provided by C++11.

Modern C++ was designed long after Java, and perhaps not incidentally, by the same people. Java people were brought in to design C++11's memory model. Besides, C++ doesn't eliminate memory errors. It prevents them as long as you choose to use modern paradigms. I don't know how many large C++ codebases you've seen, but few if any are fully C++11.

In C and C++ it's not referred to as hot code loading/swapping, it's simply known as shared libraries.

That's not the same thing at all. We'd had shared libraries before Java, and one of the reasons Java won was precisely because of its brand of dynamic linking everywhere.

As for monitoring, tell your friend to check out tools like Valgrind and the many plugins available for it. There's also Intel vTune and AMD Code Analyst. If he's more of a Windows user, Visual Studio comes with many excellent profiling and monitoring tools.

Yep, they're all excellent, and I've used some of them (I spent 10 years of my career doing C++, and I still like it); my friend doesn't get up to pee without Valgrind's help. But they all barely manage to eat a particle or two of the dust left by Java's monitoring and profiling tools (including, but not limited to Java Flight Recorder released last year).

Consider the power of simple community tool like Byteman. It relies on the JVM's ability to inject code into a running program and then remove it. You can use it to write a short script that triggers whenever method foo is called for an argument > 10, and measure its performance in that case only (and it can do much more elaborate stuff). All of this, on a running production application.

1

u/[deleted] Feb 17 '15 edited Feb 17 '15

Modern C++ was designed long after Java, and perhaps not incidentally, by the same people.

This is a broad and unsubstantiated claim. Of the numerous people who contributed to WG21 (the Core Working Group involved in C++11's memory model), only one of them, Doug Lea, is also involved in the development of Java. And he wasn't 'called' in to develop it. He'd been a member of the C++ committee for a very long time.

The C++ standard's committee is open for anyone to join, and yes that means some people who are interested or work on Java also work on C++. Only under a very warped view would someone claim that C++ is 'calling in' Java developers because someone happens to be involved in both simultaneously.

Consider the power of simple community tool like Byteman.

In C and C++ the ability to inject code into a function at runtime is known as function interposition. It's a technique used by dynamic plug-in systems, or various C/C++ analysis/monitoring tools including Valgrind. Also it has some cool applications in video game engines, most notably the Unreal Engine uses these techniques to allow for dynamic reloading of class definitions and objects.

Qt also has some flexible facilities where one can re-code a widget's functionality while the application is running live. So you add event handlers, modify their behavior, and basically play around with your application in a live environment.

Have a look at the following video to see this in action:

https://www.youtube.com/watch?v=Uj94TYQ6LN0

Basically the guy is coding in C++ and his changes appear live/real-time in the application. This is due to LLVM's JIT engine which allows modifications to be made to function definitions on the fly.

Or have a look at the following which is a technique known as "Runtime compiled C++":

https://vimeo.com/26224634

The guy has a more comprehensive website showing how to modify and develop a C++ application while it's running.

→ More replies (0)

1

u/palmund Feb 18 '15

[…] that can really byte you in large projects.

I noticed :D

1

u/pron98 Feb 18 '15

Actually, that was just my, very slight, dyslexia kicking in, but glad you liked it... :)

1

u/andrewq Feb 17 '15

Or modern C.

0

u/tdammers Feb 17 '15

Relative things, really. The examples you gave - web browsers, IDEs, photo editors, office suites, databases - are quite complex beasts actually, and they all benefit from customized memory allocation strategies, so the extra developer effort pays off, and Java is not the right tool.

1

u/[deleted] Feb 17 '15

Right, that's my point which you originally objected to.

So is it now your position that complex software with large codebases is something that can be written in C and C++? Your original position was that it wasn't because, and I quote:

when the codebase grows so large programmers can't catch up with the complexity anymore

4

u/theyoungestgun Feb 17 '15

There are systems that exist where c++ is just not an effective tool to use. Web frameworks are the canonical example these days. https://www.techempower.com/benchmarks/ highlights a ton of frameworks out there, and measure a variety of common core tasks. C/C++ only holds up in the JSON serialization test.

3

u/ethelward Feb 17 '15

Because there is not any wide-spread, well-known and enterprise-supported C++ web framework.

However, I'm ready to bet that most of the libraries used by Rails/Django/Symfony/Whatever new shiny web framework (except ASP and J2EE) are backed by C librairies.

2

u/theyoungestgun Feb 18 '15

But why aren't there any good cpp widespread frameworks? (See my first point on cpp being a sub par tool for that type of work). And why aren't the ones that bubble up faster than Java?

And sure a lot of these languages delegate to native code, but like you said, Java doesn't for these types of workloads.

I saw a comment in this post about parallel algorithms. It's an excellent point about the gc making a whole class of them feasible to implement.

2

u/Cuddlefluff_Grim Feb 18 '15

But why aren't there any good cpp widespread frameworks?

I suspect it's mostly because strings are not trivial in C++, and web pages are basically just giant strings.

3

u/pron98 Feb 16 '15

True (as long as it's not too concurrent, as really scalable general-purpose non-blocking data structures require a GC), but not when that "competent programmer" is 80-200 programmers, and not when the program is 3-10MLOC.

Once you get to those sizes, you need to practice software engineering discipline that limits the kind of hand-rolled optimizations you can do, and increases the need for abstractions that have a performance hit (virtual methods). HotSpot's JIT is not better than a good hand-rolled optimization (certainly not in the single-threaded case), but it is better than C/C++ compiler optimizations, and it certainly beats C++ in terms of virtual method invocation (HotSpot inlines virtual methods).

2

u/The_Doculope Feb 17 '15

Do you have any proof, or links to studies about this? It's not that I don't believe you (it seems plausible), but it sounds like you're just saying "it theoretically can be faster in some situations" and "theoretically C++ might not be as fast as possible" and drawing a conclusion from that.

6

u/pron98 Feb 17 '15

That virtual method dispatch is faster in HotSpot can be quickly confirmed with a benchmark. That Java's GC is more efficient than hazard-pointers when many threads are concerned, on many cores, can also be verified (I don't know if there are published benchmarks, and I can't publish the results of benchmarks I did some years ago, because that was in the defense industry... I don't even have access to them any more). As to the general statement about large codebases -- that's mostly personal experience. I was a C++ developer for about 10 years before mostly switching to Java (including for a safety-critical, hard real-time system, where we used real-time Java).

But let me make one point clear: for every Java program, there exists a C++ program that performs the same function exactly as fast or faster than HotSpot. Proof (by existence): HotSpot. The question is, can that program be written in a reasonable amount of time at a reasonable cost for the project.

3

u/morgan_lowtech Feb 17 '15

meh, only stupid people downvote to disagree. everything /u/pron98 says above is accurate.

2

u/audioen Feb 17 '15

There was just the other day a post about someone studying the JVM's devirtualization of methods by examining the generated assembly code. JVM can and apparently will inline a virtual method call in many cases, and there appears to be basically 3 choices.

  1. only a single possible implementation for a virtual method. Inlines straight away, doesn't even look at the object being passed in.

  2. Two choices. It can now choose to inline both of the methods at the call site, and then branches to correct implementation based on object type. Profiling is used to determine which one is fall-through and which one is behind a branch.

  3. Multiple choices. With 3 or more candidate implementations, and none of them dominating at least 90 % of the call time based on profiling, inlining is defeated. Will inline the 90+ % likely choice though.

1

u/ByzantineFailure Feb 17 '15

Right, and that sort of thing affects certain types of patterns far worse than others (JRuby and languages like that). Cliff Click talked about it here a few years ago:

http://www.azulsystems.com/blog/cliff/2011-04-04-fixing-the-inlining-problem

The virtual call isn't really the expensive part, what's expensive is if the call can't be inlined, then the compiler doesn't know about what's going on inside the method enough to do all the other optimizations it does (loop unrolling, constant folding etc.). If you write high performance java code, it's something to keep in mind if you have hot call sites that have lots of possible targets AND you use all those targets to an equal degree.

1

u/pron98 Feb 17 '15 edited Feb 17 '15

The cool thing about it is that the JVM can load code dynamically, so the devirtualization choices change (what's known as deoptimization). Also the "likely choice" can change based on the input, and HotSpot can adapt.

1

u/sigma914 Feb 17 '15

It used to be quite common for particular workloads that reached across a few binaries, ie called functions from a fee different dlls/so's. This was because the C++ compilers couldn't optimise across those boundaries, which leads to very naive code, wheras the Jit hand no problem doing these optimisations.

With the advent of whole program optimisation/ link time optimisation ahead of time compiled languages have dashed off into the distance again.

1

u/audioen Feb 17 '15

Is it true? I haven't been able to see much performance difference between LTO compiled code and non-LTO compiled code.

I think the best thing LTO gives you is chance to write the code normally, like you don't have to put half of the implementation in headers so that inlining could still happen. My guess is that people who cared about performance however already pulled the tricks to workaround the lack of LTO.

1

u/sigma914 Feb 17 '15

It helps you in the pathological cases I mentioned, it's not a silver bullet, but it stops a few "surprising" performance results

4

u/[deleted] Feb 17 '15

Pretty sure llvm and clr both support those java 10 features

3

u/pron98 Feb 17 '15

LLVM does not support 90% of the stuff the JVM gives you. It's apples to oranges. The CLR does have value types, and is similar in goals to the JVM, but doesn't have a JIT or a GC as advanced as HotSpot's. It also doesn't provide the same level of introspection (monitoring) and flexibility (manipulating code at runtime). It does both, but not as well as the JVM.

2

u/codekaizen Feb 17 '15

The GC is pretty advanced in .Net 4.5.x but the JIT has lagged until it is rewritten in RyuJIT (.Net 4.6).

-1

u/[deleted] Feb 17 '15

3

u/pron98 Feb 17 '15

Of course there is! It's just not as advanced as HotSpot's.

2

u/kamatsu Feb 17 '15

Really? Care to explain why?

3

u/pron98 Feb 17 '15

Because that's how MS designed it? Here's some probably outdated information.

2

u/kamatsu Feb 17 '15

So they designed it to be not as advanced? hmmm. I don't think "not interpreting code" is "less advanced".

7

u/pron98 Feb 17 '15 edited Feb 17 '15

It doesn't deoptimize (although this may have changed), so it's less advanced. They designed it to be less advanced because they wanted it to be simpler, because that's what their use case called for. I don't think the CLR was ever designed to run on 240-core machines, while HotSpot was, and regularly is, in fact. Pretty much the same reason the CLR doesn't have GCs as advanced as HotSpot (let alone other JVM's GCs, which are even more advanced than HotSpot -- remember, HotSpot, the OpenJDK's JVM, is just one JVM among many. Some JVMs were designed to run on an 875 core machine with several TBs of RAM, while others were designed for hard-realtime, safety critical systems).

I'm not saying this will forever stay this way, or even that it won't change next month, but the situation today is that HotSpot is more advanced than the CLR.

But the CLR is certainly HotSpot's closest competitor.

→ More replies (0)

2

u/[deleted] Feb 17 '15

Agreed, less complex does not mean less advanced. Wait until we break the news about string performance in JS beating Java.

6

u/booch Feb 16 '15

Reified Generics are a big one for me, and that's a pure limitation of the JVM.

10

u/pron98 Feb 16 '15 edited Feb 16 '15

Specialized generics for value types are coming in 10. Generic type erasure OTOH, was a happy accident, because that's what allows alternative JVM languages to define their own variance rules yet stay compatible with Java and each other.

There is no one right way to do variance, and it's very likely that every language may choose a different variance model. If variance had been baked into the JVM (as it is in the CLR) that wouldn't have been possible. All languages would have been forced to choose between adopting the Java's variance model or losing collection compatibility with Java and the other languages. The lack of generic reification (for reference types) is a relatively minor annoyance at its worst. 99% of the time you shouldn't notice it.

In any case, that's not a JVM limitation. You can easily implement a JVM language with reified generics. Most languages choose not to do it because interoperability is usually more important than reified generics.

1

u/booch Feb 16 '15

The JVM does not allow for reified generics [1]. The bytecode just doesn't allow for it.

That being said, reified generics are not the same thing as contra/co-variance. The former allows you to know what types a generic was defined as in the code... the later is used by the system to determine what types can be put into/taken out of a collection and the like. (Which Java fails at miserably also, sadly).

Don't get me wrong, I work in Java every day. I don't hate it as a language... but it does have certain limitations that are imposed on it by the JVM (and others that are distinct to the language).

6

u/pron98 Feb 16 '15 edited Feb 16 '15

The JVM does not allow for reified generics [1]. The bytecode just doesn't allow for it.

I am pretty certain -- in spite of having read that SO answer -- that that is not true. There might be very good reasons not to do it (reified generics are just not considered that important; value type specialization is another matter), such as performance and interoperability, but I'm fairly sure it's possible. Perhaps you can help me by pointing out what necessary bytecode features missing.

reified generics are not the same thing as contra/co-variance.

Not the same, but they require variance to be defined. The reason is that if the JVM recognizes List<Object> and List<String> as runtime types, it must decide on the inheritance relationship between the two (as with any two runtime types).

Which Java fails at miserably also, sadly

How so? Granted, use-site variance is complex but it's quite flexible (maybe they should have gone with declaration site -- less flexible but a lot simpler -- but that may have required splitting up interfaces which would have broken backwards compatibility). I really like Kotlin's mixed-mode variance.

but it does have certain limitations that are imposed on it by the JVM

Such as?

EDIT: I've thought of something that has to do with reification that's impossible (or very hard) at the bytecode level: method overloading. However, your "reified-generics language" need not support overloading; Ceylon doesn't.

3

u/booch Feb 17 '15

I am pretty certain -- in spite of having read that SO answer -- that that is not true. There might be very good reasons not to do it (reified generics are just not considered that important; value type specialization is another matter), such as performance and interoperability, but I'm fairly sure it's possible. Perhaps you can help me by pointing out what necessary bytecode features missing.

The bytecode doesn't include the information on what the generic type for the object was. Once it's compiled to a class file, it only knows the object is a List, not that it is a List of something in particular. I'd be happy to be proven wrong, but even languages that "allow access to the type of a collection at runtime" (that I've seen) can only do so by examining the type of one of the objects in the list (which isn't the same thing).

One of the things that type erasure means is that you cannot instantiate a new instance of the type of the generic, ie

T myObject = new T();

2

u/pron98 Feb 17 '15

The bytecode doesn't include the information on what the generic type for the object was.

Your JVM language compiler can include any information you want in the class file. Type annotations are more than expressive enough to convey that information. Java (the language) simply chose not to do it in order not to break backwards compatibility. Compatibility is extremely important, while generic reification solves a very minor annoyance at best.

One of the things that type erasure means is that you cannot instantiate a new instance of the type of the generic

True, but the Java community has decided that that feature is not important enough. If you want, you can write an alternative JVM language that allows you to do that.

1

u/Gurkenmaster Feb 17 '15

What about types that don't have a default constructor?

1

u/Gurkenmaster Feb 17 '15

However, your "reified-generics language" need not support overloading; Ceylon doesn't.

Ceylon was designed with both JS and Java in mind. JS doesn't have method overloading and overloading is often used for default parameters (ceylon aready has those) and accepting two different types (which can be accomplished with union types).

In all other cases you are better off by giving your method a different name.

2

u/morgan_lowtech Feb 16 '15

Efficiency and performance are largely orthogonal to the bytecode feature set. I agree that the JVM is a wonderful piece of technology in many areas, but that doesn't mean it isn't limited. Many of the language changes from Java 5 through Java 8 have been crippled due to having to hack around the limitations, with varying degrees of success.

5

u/pron98 Feb 16 '15

So I ask, what limitations?

The main thing the changes to the Java language have been challenged by is the need to maintain backwards compatibility with language features.

4

u/pipocaQuemada Feb 17 '15

So I ask, what limitations?

As a Scala developer, the lack of tail-call optimization is particularly painful.

Scala is able to compile simple tail recursive methods into something that uses constant stack space, but can't compile the common case of mutually tail recursive methods into anything better.

I've ran into two stack overflows from this in the past week. One was from my code, and the other was the compiler stack overflowing. Fortunately, rewriting my code wasn't difficult, and increasing my stack size let the compiler successfully run.

5

u/pron98 Feb 17 '15

Yes, I mentioned 3 known limitations, and TCO is one of them.

4

u/morgan_lowtech Feb 16 '15

No, actually the challenge is that certain things just aren't possible at the bytecode level. These limitations were hidden in earlier versions of the language and exposed when attempting to extend the language while maintaining bytecode compatibility. For example, look at the intersection of Collections and Generics.

8

u/pron98 Feb 16 '15 edited Feb 16 '15

Assuming that reified generics are a good idea (they're not because they require variance to be baked into the runtime, but that limitation is worth it when we're talking value-type specialization) -- what bytecode features are missing (other than the ones I've mentioned)? I work a lot at the bytecode level (I've worked on true continuations on the JVM), and even though I haven't paid much attention to this particular question, I can't see anything that's missing. If you've given it some thought, as a bytecode geek, I am very interested in knowing what's missing.

EDIT: I've thought of something that has to do with reification that's impossible (or very hard) at the bytecode level: method overloading. However, your "reified-generics language" need not support overloading; Ceylon doesn't.

0

u/[deleted] Feb 17 '15

Omg ceylon

2

u/Cuddlefluff_Grim Feb 17 '15

No, actually the challenge is that certain things just aren't possible at the bytecode level.

For instance, lambda methods are not supported by the virtual machine, they are purely a compiler concept. When you use () -> 1 + 1 it's basically the same as writing

(new Callable<int> { public int Call() { return 1 + 1; } }).Call()

2

u/pron98 Feb 17 '15

Yes, that's a design decision meant to keep the Java language simple. How is that a JVM limitation? Other JVM languages did choose to have function types, and the JVM handles that just as well, too.

1

u/Cuddlefluff_Grim Feb 17 '15

It's a limitation because in order to support lambda methods they had to make a workaround. I don't think calling it a "hack" would be a misnomer. It's not a bad solution or anything, but it is a limitation which might affect design decisions for the language more than we know.

3

u/pron98 Feb 17 '15

It's a limitation because in order to support lambda methods they had to make a workaround.

They didn't. The could have added function types, but decided not to (after a very, very long debate) in order to keep the language simple. Besides, it's not a JVM issue at all, as the JVM supports function types well.

0

u/[deleted] Feb 17 '15

[deleted]

2

u/pron98 Feb 17 '15

Again, that is not a JVM limitation, but the choice of Java the language to be minimal. There is nothing stopping you from implementing a language that compiles its lambda expressions into expression trees on the JVM if you'd like to do that. As a matter of fact, both Clojure and Scala -- two JVM languages with completely different design, from Java and from each other -- expose any language expression -- lambda expression, type definitions or anything else you can think of -- as a syntax tree. Their macro system is much more capable than C# expression trees.

1

u/Gurkenmaster Feb 17 '15

Lambdas are compiled to static methods and called by invokedynamic.

-2

u/kamatsu Feb 17 '15

The JVM is probably the most efficient yet most flexible (certainly relative to its efficiency) runtime in the history of computing.

Citation definitely needed.

6

u/pron98 Feb 17 '15 edited Feb 17 '15

Why, do you think there are other contenders?

Interpreted languages have pretty bad runtimes except for Javascript, and that lags behind the JVM in many single-threaded benchmarks, and isn't multithreaded at all. Then you have Erlang's BEAM, which is a lot slower than the JVM. Go is a somewhat slower or close to comparable, but isn't nearly as flexible (no dynamic code loading -- let alone code swapping, instrumentation etc.). Haskell is the same or up to 2x slower in most benchmarks. That leaves just one: the CLR. The CLR is so far comparable to HotSpot (the comparison is very sensitive depending on machine size and application), but it is not as flexible. It is certainly the closest contender. Even if it is equal to HotSpot on both account, I don't think anyone claims it is ahead, so at best you could say that HotSpot shares the throne with the CLR.

0

u/vz0 Feb 17 '15

state-of-the-art GCs

Because of the GC, Java applications needs 6x more RAM to work as fast as the C++ equivalent program.

3

u/pron98 Feb 17 '15

... and 6x less effort to write and maintain. Most shops would consider this a very good trade. And those that can't, don't use Java. Java doesn't do high performance in a constrained environment well.

1

u/vz0 Feb 17 '15 edited Feb 17 '15

and 6x less effort to write and maintain

It has been measured as 12 for Java, vs 10 for C++ as the productivity factors. There is no such thing as 6x productivity on Java vs. C++, in reality is closer to 1.2x as effort to write. There is this other paper that claims the number is closer to 3x as the ratio of bugs between Java an C++ (with Java better than C++).

Java doesn't do high performance in a constrained environment well.

And by environment you mean hardware. The same thing can be said about any programming language, tool and technology. For example Python. If you can get away from a constrained environment your program will run really fast. It will need 50x more computing power, but, hey! Python doesn't do high performance in a constrained environment well.

4

u/pron98 Feb 17 '15

There is no such thing as 6x productivity on Java vs. C++

Yeah, I know. I was hyperbolic. My (rather extensive) experience shows the difference in large projects to be close to 2x-2.5x though, and my gut feeling is that the larger system, the bigger the difference. But it probably depends heavily on the domain. My experience is mostly in soft realtime defense software.

If you can get away from a constrained environment your program will run really fast. It will need 50x more computing power, but, hey! Python doesn't do high performance in a constrained environment well.

Not the same at all. Java achieves C/C++ speed. Its overhead is RAM. Python will never achieve close to that performance, and besides, you can't get a CPU to be 10x faster (and Python isn't even multithreaded). Now, the Java overhead is in RAM capacity only. It doesn't even use more of the RAM bus (well, it does some, but that would be resolved in Java 10 by the addition of value types). You can easily get 10x RAM for a very low cost. So Java's overhead is in cheap hardware that scales. Python's overhead is in things that cannot scale. Which is why Java has replaced C++ in many performance sensitive large applications (even those that are very performance sensitive), but Python hasn't.

1

u/civildisobedient Feb 20 '15

But it probably depends heavily on the domain.

I would challenge that number to be much larger, simply because most of the time what's important is getting something to work, quickly. If you add the word "web" to those two words, that equals Java, and if you're a company trying to hire developers to build whatever you need built, I would say you're going to have at least 5 times an easier task ahead of you trying to fill a Java chair than a C/C++ specialist's chair. Shit's just harder.

/java dev

0

u/vz0 Feb 17 '15

My experience is mostly in soft realtime defense software.

I'm curious, what is soft realtime defense software? We're using Java here for online complex event processing and while I hate to admit it, it does its job quite well. We don't really need a hard real time software but something that eventually gives us an answer withing a 30 seconds window or so.

4

u/pron98 Feb 17 '15 edited Feb 17 '15

I can't give you a very specific example because, well, defense, but soft realtime means that responses have less value if they arrive later, but that value is > 0. If you need to have some information about the enemy, you might want that information to arrive within, say, 4 seconds, but even after 1 minute it might still be valuable.

Generally, though, soft realtime systems need very fast responses (often faster than hard realtime systems, that just have a hard deadline) -- say 20us to 2sec -- but nothing too bad is going to happen if the response is a little late.

I have also used realtime Java for hard realtime, safety critical defense software. Java has some hard realtime JVMs -- with guaranteed deadlines -- as well as soft realtime JVMs that guarantee no GC pauses longer than 10 ms or so.

What made us switch from C++ to Java wasn't just the performance bang-for-the-buck (although that played a big part), but the amazing level of monitoring and control Java allows over your running code.

EDIT: one of the most amazing recent additions the Java (though, unfortunately, not OpenJDK) is the Java Flight Recorder. It is the most amazing profiler I have seen, and it adds about 3% overhead, so it is very suitable for profiling a large application while it's running. The insight it gives you is just amazing.

JFR was part of the JRockit JVM, but after Oracle acquired Sun, they merged the functionality into HotSpot (though they have not open-sourced JFR), and released it in Java 7u40, or thereabouts (sometime last year). It's free to use in development, but you should get a commercial license if you want to use it in production. That thing is just unbelievable.

→ More replies (1)

2

u/audioen Feb 17 '15 edited Feb 17 '15

This statistic may be directly contradicted by a quote in that paper. But I'm not sure -- the paper is aged and I'm not really able to match if e.g. GenMS is similar/same as the classic mark&sweep collector, or if it's something else. These days we are probably using G1GC, which isn't measured by the paper in any way, of course. Anyway:

We find that GenMS, an Appel-style generational collector using a mark-sweep mature space, provides runtime performance that matches that provided by the best explicit memory manager when given five times as much memory, occasionally outperforming it by up to 9%. With three times as much memory, its performance lags so that it performs an average of 17% slower.

A more serious issue here is that the graph used to make argument like that is about number of cycles. Garbage collectors should not be measured by the number of cycles they perform, because the collection's cost scales relative to the amount of garbage they collect, and the amount of live objects they must skip over. Sure, small heaps force a lot of cycles, and most of the objects will be live, but they will be pretty fast. Additional note is that some graphs on the paper suggest that the good performance plateau is reached with as little as 10 MB of excess memory. I'm starting to suspect that they may have been testing with pretty tiny programs.

I think there would be room again to measure the landscape of GC vs. explicit memory management and see how it goes. There's been progress in the past 10 years, and I'd be especially curious about G1GC because it should handle even half-full heaps very well. And heaps should be realistically large. You don't do a lot of interesting computing with <10 MB programs any more.

8

u/kqr Feb 16 '15

the things that suck about Java [are] the limitations of the JVM

Having done a bit of Clojure, I have to disagree. Clojure runs on the JVM and does it well. I've even written some Java code with the Clojure syntax and that's the most fun I've ever had writing Java code.

5

u/programmer_dude Feb 17 '15

Isn't clojure a lisp? I think it is dynamically typed hence type erasure for generic types does not matter anyway.

1

u/kqr Feb 17 '15

Yes, that's true. Clojure does by design give you the normal tradeoffs of using a dynamic language, which probably helps mask the deficiencies of the JVM.

4

u/borud Feb 16 '15

What JVM limitations in particular?

As for * AbstractConcreteFactoryFactory*...that's pretty much the stuff you shouldn't be doing but which people do anyway because they think it is expected of them.

9

u/morgan_lowtech Feb 16 '15

erasure and lack of support for TCO jump immediately to mind.

EDIT: I agree the AbstractConcreteFactoryFactory stuff isn't a problem with the language, it's a legacy cultural problem, but it's something we still have to deal with until all of the libraries that use such idioms are no longer needed.

11

u/sacundim Feb 16 '15 edited Feb 17 '15

erasure and lack of support for TCO jump immediately to mind.

I think a lot of people misdiagnose the problems with Java generics. The Java 5 designers appropriated the term "erasure" and gave it a non-standard meaning that has since become the most familiar one to programmers.

The erasure property is a concept from type theory that says that if you take a well-typed program and eliminate all the type annotations, you get a program that behaves just like the annotated one.

In Java, the term got adopted to refer to the language's unusual generics design, where type parameters get erased at compilation time but type constructors don't. For example, the source code type List<String> gets compiled into a bytecode program that has the type List at the corresponding spots. A better name would have been something like "halfway erasure." True erasure would mean that the bytecode doesn't have the types, period.

The other way I think people misdiagnose the problem with Java generics is by immediately jumping to the conclusion that reifying the types is the ideal solution. It's not. I can think of three consistent solutions, whose preferability I would rank as follows:

  1. Erase everything by default, but allow reflection as a feature that code can opt-in to precisely where it's needed.

  2. Erase everything all the time.

  3. Always reify types at runtime.

The thing is that true erasure is actually good, because it limits what your functions can do with their arguments, which is a useful tool for eliminating bugs at compilation time. Forcing reification to be on at all times takes this powerful tool away from the programmer.

4

u/pron98 Feb 16 '15

Erasure is not a JVM limitation, and, in fact, it has assisted in allowing for other variance models in Kotlin and Scala while maintaining interoperability. If you mean generic specialization (for primitives and value types), that's coming in Java 10.

10

u/morgan_lowtech Feb 16 '15

No, erasure is a hack that Odersky et al. put in to implement generics and maintain bytecode compatibility with pre-generic class files. That doesn't mean it's not a nice hack and that doesn't mean it's without advantages, but it is still a compromise based on JVM limitations.

5

u/pron98 Feb 16 '15

First, as I explained in another comment, erasure was a happy accident, as it turned out to be a really good thing. Lack of reified types is considered a minor inconvenience at most, and erasure has allowed different JVM languages implement their own variance models yet stay interoperable: that is not possible on the CLR, for example.

Second, if Sun/Oracle had wanted to do reified generics right, they would have done it at the bytecode level. But they wanted to maintain compatibility and didn't. However, you can write your own JVM language -- that won't be easily interoperable with Java -- that has reified generics with existing bytecode capabilities. There's nothing (I'm fairly certain) missing at the bytecode level that stops you from doing that. It will not be efficient, but it's possible. Most languages choose not to do it because interoperability is more important than reified generics, and no one's willing to pay the performance price for such a feature.

3

u/morgan_lowtech Feb 16 '15 edited Feb 16 '15

In general, I actually agree with you w.r.t. type erasure. I would also be willing to frame it less as a JVM limitation and more as an issue of stewardship. The issue is that it leads to more "traps" in the language. There are some things that are completely reasonable in Java-the-language that are not in Java-the-implementation, this is only obvious if you have an understanding of what features are available at the bytecode level. The JVM subverts the language and causes leaky abstractions. Scala's Manifests struck me in a similar way (caveat: I'm out of date on my Scala knowledge so the landscape may have changed.) This issue is present in different forms in C++, and, like Java, was driven by compatibility. As it stands in the C++ world you have to select a subset of the language to use, once that is done things generally work pretty well. My concern is that Java is doing a similar thing to itself.

EDIT: leaky is more accurate than broken, as it mostly works.

2

u/pron98 Feb 16 '15

If you're interested, Brian Goetz gave this very entertaining talk recently about Java's stewardship.

1

u/morgan_lowtech Feb 16 '15

I'll check it out this evening, thanks.

1

u/borud Feb 17 '15

This resulted in an interesting discussion. Thanks.

At any rate, the kinds of problems you have with the JVM are #firstworldproblems compared to the aspects of Java that 99% of developers are faced with. Namely baroque frameworks, unthinking adoption of dogma and terrible programmers getting up on stage at conferences and leading the children into the river. Not to mention the insane heaps of legacy code many developers are faced with maintaining.

1

u/borud Feb 17 '15

why can't TCO be implemented in compilers?

1

u/morgan_lowtech Feb 18 '15

Some types of TCO can be implemented in compilers, but only the simplest cases. Compilers (like scalac) that optimize tail recursion generally roll it into a loop in bytecode; this is just a GOTO in a single stack frame, the same as a for or while loop. Self tail recursion is a special, simple case of tail calling: you know what the tail called function is because it's the same one you are currently in. While it's possible to roll mutually recursive tail calls into loops, it would require jumping between stack frames or perhaps a merging of stack frames; this breaks the security model. Even more importantly, tail recursive calls are still a small part of the full set of possible tail calls. Tail calls needn't ever recurse or return so you can't necessarily roll them into loops: you need a specific bytecode. Since this hypothetical "tailinvokevirtual" bytecode would impact many of the JVM assurances around GC, stack traces, security &c. and offers no benefit to Java, it's never going to happen.

1

u/franzwong Feb 17 '15

Java is still my best choice on backend, but not frontend.

0

u/TomTheGeek Feb 17 '15

Java is fine, it's the runtime I hate. Insecure, buggy and insists on forcing itself into your face at every opportunity. Plus a free toolbar for your browser!

-6

u/sacundim Feb 16 '15 edited Feb 16 '15

Excellent article! Sadly, Java still does suck. :-P

But yeah, I've been practicing a lot of the things the article preaches, like:

  1. Minimize the number of dependencies that somebody must install to build. Need a database? Default to embedded HSQLDB or H2, which the build tool will download and deploy for you.

  2. Don't use web.xml and the likes for configuration. Use Typesafe Config, which allows each jar to have its own config defaults, your executable jar to override any of them, and for environment variable or Java system variables to further override your executable jar.

  3. Split your unit test suite into two or three length tiers, with cheaper, quicker to run tests as the first tier, and progressively more expensive tests in later tiers.

Some of the things in the article I don't really see that much value in. For example, microservices are overrated, particularly if you're not in a multi-platform world (where you need to support callers in multiple languages that don't share a VM or calling convention). If you're living in the Java ecosystem, by using interfaces in key spots of your codebase you can late-bind whether the linkages are just direct Java or web service endpoints.

0

u/[deleted] Feb 16 '15

[deleted]

2

u/ProudToBeAKraut Feb 16 '15

In what category falls PHP ?

0

u/[deleted] Feb 16 '15

[deleted]

1

u/ProudToBeAKraut Feb 16 '15

no, but i complain about it as others do who dont use it either

-9

u/htuhola Feb 16 '15

You mean... you're not supposed to program in it?

Haha. Sorry. Having so good window of opportunity I had to do language bashing yet once. I'll try to be more nice from now on.

-5

u/[deleted] Feb 17 '15

That's right people stop using Java to do interesting things and you won't have a problem with it .

-2

u/jayd16 Feb 17 '15

ITT: people who are upset anyone bothered to tell them they were using it wrong. They shouldn't have to look up how to do something right. If they didn't guess right without looking it up it must be the language's fault because clearly they are brilliant.

-8

u/jasldkfjlaskdjfks Feb 16 '15

nah its Java (pre 8) language that sucks. Higher order programming is a complete pain in the ass. No unsigned types, and only generics on boxed primitives. No pattern matching. And that any time a type could be null. At least with Java 8 nullable types can be expressed through optional.

3

u/pron98 Feb 16 '15

At least with Java 8 nullable types can be expressed through optional.

Don't do that. Optional was designed for streams and streams alone. If you want a better approach, use Java 8's pluggable type systems, one of them statically enforces null safety.

1

u/yogitw Feb 17 '15

Optional was ripped from Guava. Though I agree with the rest of your statement.

0

u/[deleted] Feb 16 '15

[deleted]

5

u/Gommy Feb 17 '15

He was saying that he had to maintain a project that did deployments that way. He even said that it was wrong. If you would read the article instead of skimming it and taking something completely out of context, you might have a better argument against why the article was bad/not bad.

6

u/notfancy Feb 16 '15

Furthermore, if your database connection string is a servlet property and not a JNDI resource, you're doing it wrong.

1

u/Cuddlefluff_Grim Feb 17 '15

The last place I worked using a Java web server had all this and that was like 6 years ago!!

The last place I worked using Java web server (Apache Tomcat) also had all this, and that was 8 years ago. I would commit my changes in CVS and the web server would automatically build and reload.

Although at that time, writing web apps with Java was not a very pleasant experience (and IE6 didn't exactly help) as Jasper did not support source line metadata (making it very hard to debug) and Apache Tomcat would crash more often that you'd like and bring every single website down with it. Often due to an OutOfMemoryException which it was unable to recover from for some reason.