Java JEP 461: Stream Gatherers
openjdk.org
openjdk.org
Java streams bring real benefits compared to other mature languages. My favorite is that sequential streams can be efficiently parallelized with a single operation, .parallel(), and sequentialized back, .sequential(), on any stream without having to configure a single knob manually (although you certainly can), an equivalent I am unaware of in any other matured language. These make operations such as .collect() and its mutable reductions leverage multiple threads for effectively 0 additional programming time.
edit: A lot of people are focusing on my favorite feature of parallelizing or serializing a stream with a single command, which apparently you can also do in C#, that was just an example guys. Other cool things you can do with Java streams natively now is leverage virtual threads (take that C#), use them asynchronously with completable futures, define how elements are accessed/gathered in streams via spliterators, etc. Streams in Java are very composable (not just as in composition, but as in utility), and enable leveraging nearly every other part of the language natively. In other mature languages, streams are very rigid and feel non-composable. I'm not saying that everything is impossible in other languages, but that in Java streams feel like a first-class citizen.
That's not actually true. .parallel and .sequential set a state flag for the entire stream. A stream that is opened, parallelized, then sequentalized, will actually just execute sequentially [1]
[1]: https://docs.oracle.com/en/java/javase/14/docs/api/java.base...
Not because of any reason other than the people using it choose to use the feature before learning about the feature.
C# has had `enumerable.AsParallel()` since .NET 4.0 (2010). Rust has rayon `input.par_iter()`.
rayon is a 3rd party library though, not part of the language itself, compared to the Java streams discussed here.
With C# I'm not sure if .NET can be called a library or not? All C# tooling ships with .NET by default or not?
> In other mature languages, streams are very rigid and feel non-composable
I'd like to see some motivating examples that make me say to myself, "Yeah, Java's got a neat trick there".
In this regard, while it is nice that PLINQ and various `Parallel`-related APIs come out of box in C#, it is a marginal difference with Rust where building parallel loops is `cargo add rayon` away.
In addition, multiple versions of transitive dependencies can coexist in Rust without conflicting with each other, there is no such risk.
When talking about projects in the wild, sure. But if we're specifically talking about language features, then "something being a part of the language" is wildly different than "installable 3rd party library".
Sometimes, it is a scar tissue from dealing with NIH syndrome too - at least you can use the OOB tools for combating with it, but the NIH itself it the actual source of people being resistant to adopting proven and good solutions developed by community.
It also means that I don't need to download the whole Internet for basic features.
Java has several 3rd party dependencies that are expected to just be there in projects where I have worked. Examples are Lombok, Apache Commons and SLF4J. These have become so widely used, that I have stopped thinking about them as external dependencies.
Guava used to be more popular too, but now that Java has Optional and Streams, I don't see it as often.
.NET is the only language ecosystem that is comparable to Java, as they are a kind of yin/yang between themselves.
In my experience, parallel streams rarely deliver a substantial performance boost. There are cases where they do, but it's more the exception than the rule. The overhead from the streams API, along with the synchronization penalties means it mostly only makes sense for coarse grained I/O laden operations.
Don't mean to detract from the point :-). I love how neat and elegant the feature is.
Can you please elaborate?
This is actually a bit of a headache on many-core machines for another reason.
e.g. my production machine has 128 cores, and carelessly parallelizing a memory hungry task (not realizing it will run across 128 threads), risks allocating sevral hundred gigabytes of RAM, and may not even be faster given all the NUMA overhead when thrashing on all cores.
Have to be careful to always down-tune the common pool size to 32 or something.
Also, that is definitely not the rule? If your problem is parallelizable by nature, parallelism provides massive speedups. Overhead from parallelizing a stream is minimal (effectively nonexistent) now if you leverage Java virtual threads (JDK 21). Additionally, most problems are not parallelizable, yes, but most solutions consist of individual steps and there is a high likelihood that at least one of those steps will benefit from parallelism. Java streams can switch between .parallel() and .sequential() execution on the go. You almost certainly don't want to leverage stream parallelism for most I/O operations, unless you leverage Java's Completeable Futures and Managed Blocking (but any gains here are probably minimal anyways) but the point is that you can leverage them, because streams in Java are a first class citizen.
> Also, that is definitely not the rule? If your problem is parallelizable by nature, parallelism provides massive speedups. Overhead from parallelizing a stream is minimal (effectively nonexistent) now if you leverage Java virtual threads (JDK 21)
This is just not true at all. Not only do virtual threads cope very poorly with I/O other than network I/O, you still get memory barriers. Virtual threads makes the memory overhead lower since you don't need full separate stacks and reduces the cost of spawning new threads, neither of which was ever an issue with streams since they use the common thread pool. Virtual threads don't significantly increase the per-thread performance.
Which is why I said you probably don't want to use the paradigm I outlined for I/O, but if you did you would want to leverage Java's Managed Blockers and async Completeable Futures for those exact reasons.
> Virtual threads makes the memory overhead lower since you don't need full separate stacks and reduces the cost of spawning new threads, neither of which was ever an issue with streams since they use the common thread pool. Virtual threads don't significantly increase the per-thread performance.
Of course virtual threads don't significantly increase per-thread performance? They make the overhead of spawning multiple threads minimal-to-zero compared to native OS/platform threads, minimizing the cost of jumping from sequential streams to parallel streams. Also, parallel streams don't have to use the global fork join pool, you can use your own fork-join pool? Which is possible in Java, because once again, streams are treated as a first-class citizen and can leverage nearly all other parts of the language efficiently and natively (although I will say Java's verbosity/boilerplateness can suck if you want to leverage your own fork-join pool, but that's widespread complaint of Java not specific to its streams)
Why does it matter that OpenMP is only a standard, rather than a language?
>my point is that Java streams are first-class citizens
They aren't. They were bolted on later and are quite cumbersome.
>without running into the rough edges you will with OpenMP.
I'm pretty sure it is easier to write fast parallel code with OpenMP than with Java streams. In fact, I am always surprised how well OpenMP works, when I get to use it.
is sure as hell not part of the C specification.
Both languages actually suffer from maturity in their tooling, because their standard build and dependency management tools (maven and sbt) are outdated and crufty, while newer languages such as Go and Rust have tooling that was built more recently, with the benefit of more recent experience.
Java by contrast will never clean up the bad, inconsistent or obsolete cruft in the language. If it is really important for you to run ancient JARs on Java 21, then the Java approach is superior.
I would never use it because I can't reason what is going under the hood, and if performance will improve or dramatically decrease because all parallel machinery has significant overhead compared to vectorized single thread logic.
I, personally, wish they never implement this parallel feature. For me JDK would be better without it.
With that said, you should almost always write a stream thinking only sequentially first, then identify steps which can benefit from .parallel() and only parallelize those steps. Its leveraging .parallel() efficiently that provides an advantage at run-time and why I tend to use it.
I get why it ended up that way. I think it would have been difficult at that time to get traction for adding FP features just as a convenience. So they needed to do all the parallel stuff to justify it. But, as I said, anyone I see doing serious parallelism in Java is not using the streams API.
I’d love to be able to ask questions and learn first hand from the people developing these.
long numberOfWords =
Stream.of("the", "", "fox", "jumps", "over", "the", "", "dog") // (1)
.filter(Predicate.not(String::isEmpty)) // (2)
.collect(Collectors.counting()); // (3)
This programming style is both expressive and efficient.
Err... I assume the author here is aware that it is neither, but perhaps struggles for something else to say in motivating this API. It's certainly an amusing remark.I'd prefer either an imperative,
for(w <- words) if(!w.empty) count++
or, an ergonomic dsl, words.filter( w -> !w.empty ).count
The strange namespacing of functional primitives, glued into an api via 'gather', 'collect' etc. is neither expressive not efficient. Though I concede it may be a necessary route for a JEP var num = words.stream().filter(w -> !w.isEmpty()).count();
This is shorter and closer to what you're expecting. The reason it's written the long way is because of the labels. The prior sentence is:A stream pipeline consists of three parts: a source of elements, any number of intermediate operations, and a terminal operation. For example: ...
so the goal here is to make the different components of the pipeline clear conceptually for the explanation of what's to come, not to write the shortest code possible. It therefore uses code that makes the underlying abstractions explicit rather than the sugar that avoids typing.
The reference to "expressive and efficient" meanwhile is likely about the fact that Java can parallelize streams in many cases (efficient). As for "expressive", well, that's somewhat debatable but for sure there are some cases where the functional pipeline style is easier to read and more expressive than the imperative style. In my own code I use both because indeed especially for short operations over lists and the like, sometimes a for loop is just clearer to my eye. But it's a matter of taste.
BTW the same code written in Kotlin:
val num = words.filter { !it.isEmpty() }.count()
Very similar. You may slightly prefer the syntax or dislike the "magical" auto-naming of the lambda parameter, I've seen it argued both ways.----
https://docs.oracle.com/en/java/javase/21/docs/api/java.base...()
As for doing things in parallel, that's where Kotlin co-routines shine.
val num = words.count(!_.isEmpty()) val num = words.count(word => word.nonEmpty)
The "bird droppings" (particularly the clever uses of _ found across Scala) were hard for me to grasp when I first started working in the language. Now they're second nature, but I try to remain cognizant of future maintainers who may be coming in to make contributions or bug fixes without first marinating in the language. val num = words.count(_.nonEmpty) val num = words.count { it.isNotEmpty() }I can appreciate its essentially a desugared version of what you'd usually write.
The JEP doesnt need to be positioned to defend this API to outsiders, but the opening part appears to do that -- but then, imv, oddly offers this example in the course of doing so.
words.filter(w -> !w.isEmpty()).count()
And they just end up calling the same methods. The author probably used "expressive" and "efficient" to refer to the underlying APIs for the fact that you can compose operations without fully evaluating the whole stream until the terminal one. words.stream().filter(w -> !w.isEmpty()).count()
Which is hardly any longer, and arguably more readable intent with the English word "filter". sum(filter(x->x%2==0,List.of(5,3,4,19,75,6)));
Streams are formatted linearly similar to Clojure threading macros.I prototyped an API that works in the same direction as streams by having something like
https://paulhoule.github.io/pidove/apidocs/com/ontology2/pid...
in that it wraps all Iterables returned by my methods and has not just the teardown facility but also all the operators attached as instance methods which lets you write the chaining style you ask for that I know is in demand.
If I was going to go any further on pidove it would have involved more use of code generation and this system
https://github.com/paulhoule/ferocity
which was supposed to be a code generator for writing code generators, and it could code generate stubs that would let you write expression trees in Java as S-expressions and build them up into methods and either compile the code to real Java source code or execute the methods by evaluating the expression tree in place.
Like common LISP you can write syntactic macros in that that metalanguage because an Expression<Expression<X>> can be evaluated at compile time, one of quite a few concepts like "quoting" that I encountered in that spike.
The idea was ferocity would get to the point where it synthesizes a more complete and perfect pidove.
It's quite clear, reading beyond just the code, that the original author is talking about _computational_ efficiency.
It feels like you missed the point — that streams are only evaluated lazily as needed — in order to poke fun at the (toy) example.
The Java code can (and in a real-world application would), be made more consise (e.g. via static imports) but the author is deliberately being more verbose to be more explicit in what's going on.
GP may be closer to the point than you realise, even if unintentionally so. I mentioned Streams failing to be lazy in another comment, and predictably got down-votes rather than corrections.
So anyway...
https://bugs.java.com/bugdatabase/view_bug?bug_id=8079264 Submitted: 2015-05-01
https://bugs.java.com/bugdatabase/view_bug?bug_id=8149614 Submitted: 2016-02-10
https://bugs.java.com/bugdatabase/view_bug?bug_id=8155217 Submitted: 2016-04-25
https://bugs.java.com/bugdatabase/view_bug?bug_id=8189234 Submitted: 2017-10-11
https://bugs.java.com/bugdatabase/view_bug?bug_id=8196106 Submitted: 2018-01-24
https://bugs.java.com/bugdatabase/view_bug?bug_id=8229983 Submitted: 2019-08-21
https://bugs.java.com/bugdatabase/view_bug?bug_id=8267758 Submitted: 2021-05-25
I wonder if 2024 will be the year of the lazy Stream.
Personally, I don't think that's what the other comment was getting at though, as they were commenting on efficiency regards to syntax.
Secondly, if I click into my first link (2015), it says resolved 2015. And by 'resolved' it means 'duplicate but not fixed'. Because when I clicked into its duplicate, it wasn't 'resolved' until 2018. What did they resolve if tickets are still being filed in 2019 and 2021?
But this is the Java Enhancement Process, and within this language AND the fact that this is specification/documentation example, this is efficient.
Efficient? Not so much. It's easy to find cases where performing an operation using the streams API comes at a 90% performance hit.
Fingers crossed that the upcoming Valhalla project can improve the situation w.r.t. number of allocations.
I've noticed a general trend where languages without support for proper compile time metaprogramming (and the corresponding optimizations) often create uglier code (despite being higher level) to avoid the performance hit. For example the mutable Vec2D type in various physics related libraries.
Last time I tested it was still faster to implement various string operations using Unsafe, than with standard APIs. I want to be able to trust my compiler/JIT.
You could use any libraries StringUtils.hasText (any serious app has one) to avoid the Predicate.not and do static imports (StringUtils, Collectors) to avoid explicitedly naming the classes containg those static methods...
Also your example misses the string collection creation part.
Ultimately we should get, put on one line like your code:
words.stream().filter(hasText).collect(counting());The person doing the shitting did not pick the examples.
let $numberOfWords := count($words[.])
or let $numberOfWords := $words[.] => count()To enable more rapid iteration, it would have been smarter to place it in a separate package of a `jdk.*` module (like `jdk.httpserver`) for which weaker compatibility guarantees apply. But that would completely divorce it from the other collection classes. Fixing that would require adding extension methods to Java.
They resisted adding any significant features at all for many years. They did gradually add some elements from languages like Scala and Kotlin, once they had proven that those features made really significant improvements to real code rather than just looking good in isolation.
It's the Honda Civic of languages. It's not especially fun and it doesn't keep up with the times. You just get in and go so that you can get something done.
That’s Golang. Java 21 is Toyota: unmatched stability, continuity and bang-for-buck in a deceptively simple shell that hides some of the most advanced tech there is.
Java's performance is fine for the vast majority of applications. Similar languages perform about as well. The JVM is an incredible piece of technology.
> It's not especially fun
I love Java, even though I don't write it much anymore.
The ecosystem is incredibly mature. There are hundreds if not thousands of high quality libraries.
Honda Civic doesn't devoure RAM.
List<List<Reading>> findSuspicious(Stream<Reading> source) {
var suspicious = new ArrayList<List<Reading>>();
Reading previous = null;
for (Reading next : source.toList()) {
if (previous != null && isSuspicious(previous, next))
suspicious.add(List.of(previous, next));
previous = next;
}
return suspicious;
}
Doesn't look bad to me. Actually the streaming example here is quite underwhelming.
It still needs a separate check for the first "iteration" (window.size() == 2). While reading the classic for-loop example I expected that especially that is something the streaming approach can handle better.In my opinion people overdo streams. I'm not sure I ever saw someone actually using the parallelization which is one of the stronger features of streams. Instead I get entire method bodies with a lot going on all shoved in one line which is for good reason discouraged anywhere else. And streams are tedious to debug. I really dislike when people (auto)refactor a 'for(var x : list) { ... }' into a 'list.stream.forEach(x -> { ... })' without any other benefit/change.
Just this week I encountered a quite crazy case where someone wrote a
IntStream.iterate(0, i -> i < getSize(), i -> i + 1).mapToObj(this::getObjectByIndex).toList()
Two anonymous classes and who knows how many extra method calls just to not write a simple for-loop where you even could initialize the list with the known size.I don't use Java day to day anymore, but I'm excited to see the language evolve. I would highly recommend watching some of the talk from the Java architects. They're very smart and have thought a lot about how to design languages. Java obviously prioritizes different things than newer language, so decisions are always made in the context of maintain backwards compatibility.
How to implement flatMap(mapper)
public final static <T,R> Gatherer<T, ?, R> flatMap(Function<? super T, ? extends Stream<R>> mapper){
return Gatherer.of(
() -> (Void)null,
(nothing, element, downstream) -> {
try(Stream<? extends R> s = mapper.apply(element)) {
return s == null || s.sequential().allMatch(downstream::flush);
}
},
(l,r) -> l,
(nothing, downstream) -> {}
);
}
Better title: how scala won the war but lost every battleis it opposite? Scala did many individual things better, but lost adaptation war maybe because of excessive complexity..
In terms of streams, it seems like this is a fancier 'pipe' ( in unix terms ), so I would have called it .pipe() instead of .gather() ... having a series of .pipe()s seems more intuitive than having a series of .gather()s on a stream.
It would be useful in more cases and have far simpler signature/interface.
Nice name. I think of:
Those Moisture Farmers of Mos Eisley have certainly updated their methods. They are even approaching the Dew Gatherers of Arrakis in efficiency.
Wouldn’t that be a bit of a nicer interface?
I think that Java suffers from NIH syndrome. Nothing that other languages do is good enough for Java until it has been debated for years and reimplemented using new patterns and unknown terminology.
Optionals that throw NPEs, Streams that operate on more than 1 item when called with .limit(1). Futures that don't cancel. Lambdas that don't play nicely with exceptions. Non-extendable streams.
It's not a coincidence that many languages that PL fans think do things "right" end up being far less popular than languages that PL fans think do things "wrong". Developers have different and conflicting preferences, and they are not distributed evenly. For example, the sweet spot for mainstream, super-popular languages over more/less compile-time checking in some areas vs. language complexity is probably not the sweet spot preferred by most developers. It's a little like the VHS vs. Betamax debate.
Improving a super-popular language in some small way that doesn't harm its popularity can have a far bigger impact on software quality than features that complicate the language to a point where it will not be taught as a first language in a lot of schools and will thus never be super-popular. Designing language features for industry to maximise their impact requires far more complex considerations than just PL theory.
I do like the Java platform in general, but this sort of argument from hypothetical future Java fixes strikes my as incredibly disingenuous. People aren't programming in a hypothetical future Java.
I can literally pose no argument against your imagined solution to this problem without very specific details. (Implication being, it's a straw man at best.)
And saying saying stuff like (in an adjacent thread):
> You're assuming that deconstructing and exhaustive patterns will continue to be restricted to ADTs only. That may or may not be the case.
Is just complete fiction. (EDIT: Are you going to solve the halting problem, or are you going to provide details before just promising "it'll be ok"? I assume the Halting Problem is out of the question, but what's the plan, then? Details, pls)
Either point to extant JEPs or explain in detail what the exact plan is, please.
Having said that, we have a few experiments with type-safe "checked exception transparency" for lambdas (and methods in general), but as always we like to sit on them for a few years because the cost of a bad feature may be much higher than the cost of a missing one. We only publicly discuss specific solutions once there's something to be gained by such a discussion and once we've decided that the problem merits a solution in the short term.
> Is just complete fiction.
I was responding to a statement about deprecating Optional in favour of an ADT, and hinted at this design, which is under exploration (https://openjdk.org/projects/amber/design-notes/patterns/pat...):
case Optional.empty() -> ...
case Optional.of(var x) -> ...
It's not complete fiction, this is actual stuff we're working on, but not everything we explore will end up in the language.You are not wrong about cancelabel futures, though.
public sealed interface Maybe<T> {
<T2> Maybe<T2> map(Function<T, T2> mapper);
<T2> Maybe<T2> flatMap(Function<T, Maybe<T2>> mapper);
T elseGet(T fallback);
record Just<T>(T value) implements Maybe<T> {
public <T2> Maybe<T2> map(Function<T, T2> mapper) {
return new Just<T2>(mapper.apply(value));
}
public <T2> Maybe<T2> flatMap(Function<T, Maybe<T2>> mapper) {
return mapper.apply(value);
}
public T elseGet(T fallback) {
return value;
}
}
record Empty<T>() implements Maybe<T> {
public <T2> Maybe<T2> map(Function<T, T2> mapper) {
return new Empty<>();
}
public <T2> Maybe<T2> flatMap(Function<T, Maybe<T2>> mapper) {
return new Empty<>();
}
public T elseGet(T fallback) {
return fallback;
}
}
}
public void demo() {
Maybe<String> foo = new Maybe.Empty<String>();
System.out.println(
switch (foo) {
case Maybe.Just(String val) -> "Hello " + val;
case Maybe.Empty() -> "Fine, leave me hanging";
}
);
}; Maybe<String> foo = null;
foo.map(s -> "bar");
explicit pattern matching is usually discouraged anyway though, and you can do this now with Optional Optional<String> foo = Optional.empty();
String message = foo.map(s -> "Hello " + s).orElse("Fine, leave me hanging");
Other languages like Scala also have an Option.fold method for this specific case.The way Pattern matching works right now is just the beginning.
The best you will get is a warning and the JVM will deoptimize Optional back to a regular object, because somewhere someone set an Optional to null somewhere in a library. It doesn't even have to be as obvious as Optional<String> o = null;
Any cast to Optional can let a null pointer slip from an Object reference. List<Optional<String>> is allowed to contain null pointers and you are allowed to assign o = list.get(0) which generates an implicit cast.
There is no good solution for this. Due to the way generics are implemented.
However, unlike the binary choice of class/value type, project valhalla will provide a more granular approach, coming with incremental performance benefits and constraints.
In the current spec draft, the type system boils down to 4 categories:
- Fully mutable, polymorph classes
- Immutable, monomorphic classes
- Immutable, monomorphic classes + null-hostile
- Immutable, monomorphic classes + null-hostile + multithreading-unsafe
Another story for nullability is being investigated as well which would allow for full performance gain as well as full backwards compatibility.
1. The rate of change that the industry demands of super-popular languages is not the same rate that PL fans demand. Java innovates a lot in, e.g., GC algorithms and low-overhead profiling because there's more demand for more rapid innovation in those areas than in language features. Java's strategy from day one is to have an innovative runtime and a conservative language (James Gosling called it "a wolf in sheep's clothing") under the assumption that that's what the industry wants. So far, that strategy has worked very well.
2. Because Java will likely continue to be super-popular for many years to come, it's more important to avoid introducing harmful features than to introduce beneficial ones. If you've introduced a "good" feature five years after a less popular language introduced it, you've only lost five years of possible slightly better productivity; if you're introducing a "harmful" feature, you've harmed your language for decades to come. Super successful language need to think more more long-term than languages vying for more users right now.
However languages are not startup companies trying to sell a product, it's the other way around. The popular ones are largely driven by industry to suit the industry needs, which are largely very conservative. Nobody wants another Perl 6 or Python 3.
Another example that people often ask about is named and default parameters. It looks like lots of languages have them, but the problem is that it's usually implemented in a way that harms those languages. For example, C#, Kotlin, and Swift all generally try to support separate compilation and binary compatibility, but their named & default parameters break that. We'll only add the feature to Java once we know how to do it right (something that I think no other language that cares about separate compilation has done yet), and we have some ideas.
And I disagree that FP features are awkward to use in Java (well, some pure-functional theorems don't work because of null, but they also don't work because of reflection, anyway, and they don't work in most non-pure-FP languages, either).
> And I disagree that FP features are awkward to use in Java
Two words: checked exceptions.
A feature contributes such value ones there's some reasonable combination of productivity benefit and demand, and that combination differs over time; the same feature can have more value in, say, 2015 than in 2005. The difference can be because the kind of software people write is different, the hardware is different, or fashion is different (which affects demand).
> Two words: checked exceptions.
Checked exceptions come into play primarily when there's IO or other side effects involved, so we're already in an area that isn't entirely functional and there are special challenges with FP, anyway. Checked exceptions are rare in pure computation (and arise there primarily around parsing strings). I fully acknowledge there's a problem in the interaction of checked exceptions and functional combinators (and we're exploring solutions), but while it makes functional composition of IO cumbersome, I wouldn't go so far as to say that it makes FP awkward.
BTW, while it is certainly not as elegant as it could be, combining IO with FP is already much better in JDK 21:
<T> Result<T> doManyIOTasks(List<Callable<T>> ioTasks) throws MyException {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
var ts = ioTasks.stream().map(scope::fork).toList();
scope.join().throwIfFailed(this::handleException); // handle/rethrow exceptions
// all IO is done & no more checked exceptions here; we can now do functional processing
return ts.stream().map(Supplier::get). ...;
}
}You're acting as if Java is just reacting to what people are demanding - but I think that Java has been actively shaping how people learn programming for several decades now, and so should take responsibility for it.
> I fully acknowledge there's a problem in the interaction of checked exceptions and functional combinators (and we're exploring solutions)
Why does it take Java 10 years to fix something that other languages have done correctly from day 1? Swift has "rethrows", what's wrong with just adopting a similar approach?
Obviously it's a combination of both, but education about programming paradigms is not the ultimate goal. All features are there to serve the goal of producing working software. Of course, we add new features to serve that goal and to use them requires education but there's only so much you can educate your market to change their habits. You have to do it slowly, as we're doing now with ADTs. Also, PL fans tend to overestimate the actual impact of language paradigms. For example, for years Haskell fans have said that their paradigm leads to significantly more correct programs, but research hasn't found much evidence to support that. For various theoretical and practical reasons (some of which were predicted long ago), programming languages now see diminishing returns, and productivity differences between languages in similar domains are not that big.
The other languages in Java's very small club of super-popular languages are JS and Python (and to a lesser degree C and C++). They're not very innovative language-wise, either, because you can't be unfamiliar and popular. The under-20-year-old languages that are doing very well are TypeScript (which does innovate in the language but in the field of how to add gradual typing to JS) and Go (which is less innovative than Java).
Trying out novel language approaches and seeing how much of an impact they actually make (which is growing ever smaller) is the job for less popular languages. We try to pick ideas that have proven themselves after years of practice.
> Why does it take Java 10 years to fix something that other languages have done correctly from day 1?
Sometimes it's because they haven't done it correctly enough and the problem is harder than it seems, and sometimes we just have more urgent things to do.
> Swift has "rethrows", what's wrong with just adopting a similar approach?
Maybe nothing; maybe the fact that it doesn't work with streams (where exceptions thrown by lambdas aren't thrown by the intermediate operators but by the terminal operation). But whether its something like this or something completely different, we have more urgent things to work on.
Except, you know, that thing Steele said about dragging C programmers halway to Lisp, which can be seen as describing and educational attempt.
Unfortunately, since Java 9 the rate of change seems to have increased a lot.
> You don't need to waste time on language churn, can spend the entire time building stuff instead.
In my experience, every time you upgrade to a new Java LTS, either something breaks or a library you depend on is incompatible with that Java LTS, and you have to waste some time fixing the breakage (the most recent one I saw: latest Mockito is incompatible with Java 21, unless you set a magic system property).
The only feature that really got obsoleted is the Security Manager and the underscore variable name. Primitive wrapper class constructors are on the chopping block next. Most other things are merely being restricted to harden the platform, with ample time to prepare.
Edit: LTS hopping is probably an unwise strategy as one will harvest only disadvantages: few updates, no performance improvements, no new features, and complicated migrations when it is time to upgrade. One best upgrades as soon as the new version becomes available (as people did before Java 8) or stays on LTS until the software is retired.
That was not the case a couple of days ago when I last looked; I see now that they released Mockito 5.7.0 two days ago, which probably fixes this issue. But that still shows my point: for every new Java LTS, you have to either fix some breakage, or update some library you depend on to a new version (which might then require further changes to your code, or even dropping compatibility with some older Java LTS).
Edit: I just tried with the latest Mockito (5.7.0), and it still gave me the same "Java 21 (65) is not supported by the current version" error, when run without the magic system property. It seems something else earlier in the dependencies had a dependency on an older release of byte-buddy, so I will have to manually upgrade byte-buddy, and hope that it doesn't break that earlier dependency.
I upgraded to JDK 21 on the day of release and haven't had issues with mockito (or spring, hibernate, junit, etc.)
I needed to bump the version of guice, but beyond that it was a very smooth transition.
Since Java 9, they don't introduce changes, they introduce new features which is a bit different.
IT is a field that (should) attract people that are for fast paced environments, not old school slow-to-innovate industries.
Stream's terminal operations contains much more options than just "creating a list".
They are in toy examples.
I don't follow your original point 100%, but I will say that 90% of the time when I use Streams, I'm really just wishing List had map and filter, etc.
https://github.com/openjdk/jdk/blob/master/src/java.base/sha...