13 ms·
Java 8 Features
If you haven’t seen some of the videos or tutorials around Java 8, you’ve probably been super-busy or have a more interesting social life than I do (which isn’t saying much). With new features like lambda expressions and Project Nashorn taking so much of the spotlight, I wanted to focus on some new APIs that have been a bit under the radar, but make Java 8 better in so many ways.
- xxs 12y agoStampedLocks have been talked about extensively at least on jsr-166 mailing list and they required adding load/load barrier in sun.misc.Unsafe. That was the prime reason it needed Java 8, as previously it required a no-op CAS on the load path. For most people StampedLock will remain quite a mystery as they are harder to use and the vact majority of Java developers doesn't actually write (or even use) low-level concurrency primitives.
- qwerta 12y agobut for many frameworks StampedLock is big progress.
- Someone 12y ago"StampedLocks have been talked about extensively at least on jsr-166 mailing list" Isn't that the jsr that designed StampedLock and decided to add it to Java? If so, I would hope it was talked about extensively, but I wouldn't see such talk as a counterexample.
- xxs 12y agoThat's the thing: people who are interested in them (StampedLocks) were already subscribed on the list. Like I've mentioned - outside there is close to no interest on low-level primitives, down to CPU memory barriers.
- thescrewdriver 12y agoIt's a nice performance improvement over ReadWriteLock as anyone who's ever tried it will know that RWL pretty slow.
- xxs 12y agoYes, RW-Locks have update (CAS) on the read path which prevents them from scaling.
- Mister_Snuggles 12y agoThe new Date API will be a big win for new developers. I think it was created by the same person that made Joda-Time, so there's some real world experience behind the new API. I also like the easy parallelization functions, though as the article indicates they're not suitable for every use case.
- MrBuddyCasino 12y agoAbsolutely, good thing they've learned from the java logging disaster. I nerdrage so hard every time I think about it - how can one mess up something so basic, yet so important? Maybe some sunny day, they'll fix that too.
- mooism2 12y agoI'm curious (it's a long time since I programmed in Java) - what is the java logging disaster?
- thescrewdriver 12y agoJust about every project used Log4j. When they added logging to the JDK they shipped logging support which was worse than what everyone was already using (log4j), so adoption was very limited.
- jburwell 12y agoWhich in turn gave rise to the horrors of commons-logging (clogging) attempting to wrap both APIs and magically detect your logging framework with nasty classloader tricks. While slf4j is a very sane and useful wrapper, it shouldn't be necessary -- JDK logging should have been the wrapper API providing an SPI to plugin implementations (e.g. log4j, logback, etc).
- MrBuddyCasino 12y agoRight - fixing it in that case means "do the same as thing as with Joda, but do it with slf4j and logging instead".
- thescrewdriver 12y agoThe best part is that these classes are available for use in other JVM languages. I'm more likely to use these from Scala than I am from Java.
- dopamean 12y agoI was just thinking the same thing. I'm more likely to use them in Clojure. Pretty cool.
- ZoFreX 12y agoThe process control changes might not seem so exciting but they fix some serious pain points, I'm very excited to integrate these into my code. Optional is another nice addition, I've been creating one myself in all Java projects I've created since I first encountered it in Rust.
- maaaats 12y agoAnd now frameworks can finally supply Optionals, since it before only lead to multiple competing implementations.
- mike_hearn 12y agoBut is it really better than @Nullable?
- jburwell 12y agoCompletely different concepts. @Nullable expresses an precondition indicating whether or not something can be null. One example of its use is by static analyzers such as Findbugs to find misuse to APIs. In contrast, Optional encapsulates the behavior when something is not present (or null) -- very similar to the Null Object pattern [1]. Used together, you can build an API that permits encapsulates the present/not present behavior and ensure that it is not passed a null reference to the Optional instance. [1]: http://en.wikipedia.org/wiki/Null_Object_pattern http://en.wikipedia.org/wiki/Null_Object_pattern
- vog 12y agoIt is a pity that Qt is not mentioned in that article. AFAIK, It is the only widely-used C++ library that implements null objects consequently. Ever wondered why the Qt framework doesn't use any exceptions or C-style error codes? It is solely because of proper use of Null objects.
- DCKing 12y agoOf course it's better than @Nullable. @Nullable-annotated code still compiles your NullPointerException-throwing code, using Optional won't.
- bicx 12y agoWish Android would move in this direction. We're stuck in a 1.6 API for the most part.
- jwn 12y agoI was confused by this comment, because the last time I heard Android was on a 1.5 equivalent. But sure enough as of ADT 22.6.0 (March 2014) some Java 1.7 features were added: http://developer.android.com/tools/sdk/eclipse-adt.html http://developer.android.com/tools/sdk/eclipse-adt.html
- krschultz 12y agoAndroid is 1.6 equivalent with some of the syntactic sugar of Java 1.7, but none of the Java 7 or 8 APIs (NIO, new date library, optionals, lambdas, etc). Unfortunately the legal fight between Oracle & Google has really made me doubt that the cool new language features will be coming any time soon to Android.
- higherpurpose 12y agoGoogle is not going to try and advance Java development. They should just deprecate it and switch to Go. But right now they seem stuck in the middle, not doing either.
- bicx 12y agoI really hope they don't. Go is really good for some things, but true object-oriented languages are great for designing and controlling UIs.
- nkozyra 12y agoHm, I think the way Go uses interfaces would actually be ideal for manipulation of UI.
- nostrademons 12y ago
- dschiptsov 12y agoNo one sees an irony?)
- theandrewbailey 12y agoHow so? Is it no one is talking about new Java features is because Java isn't the hot new web stack or JS library? Or because most big Java users move to new things with the speed of continental drift?
- smoyer 12y agoWe're a big Java user but apparently faster - our current environment is JavaSE 7 and JavaEE 6. We'll move to JavaEE 7 when there is commercial support for an application server (probably JBoss EAP 7.0.0) and will likely allow Java SE8 at the same time. We're quite a bit slower at migrating existing applications (except for security issues), but because we code defensively, we are generally backwards compatible.
- goblue96 12y agoI can't wait to do code reviews where people are sprinkling parallelSort() all over the place, not understanding the consequences. Serious question: isn't this something the JVM could abstract away?
- reitanqild 12y agoEqually seerious question: Didn't you just answer you own question before you asked it?
- goblue96 12y agoNo, I didn't. If, for even an instant, you ever buy the argument that a JIT is better for real-world application tuning than static code analysis, you see my point.
- bhauer 12y agoGood point. There is definitely a challenge of knowing when a single-threaded collection or stream operation may be preferable to the parallel option. When my colleague wrote his summary of Java 8 [1], he wrote: Returning to the concept of parallel streams, it's important to note that parallelism is not free. It's not free from a performance standpoint, and you can't simply swap out a sequential stream for a parallel one and expect the results to be identical without further thought. There are properties to consider about your stream, its operations, and the destination for its data before you can (or should) parallelize a stream. For instance: Does encounter order matter to me? Are my functions stateless? Is my stream large enough and are my operations complex enough to make parallelism worthwhile? The author of the linked InfoQ article (OP) cites that same dilemma by explaining the potential for context-switching overhead to counter the advantage of splitting the work. Abstracting it away with rough heuristics might be possible, but doing so with consistent success could be challenging. In other words, you could elect to use the serial algorithm for small collections, or when the CPU contention at the start of the sort operation is low. But if the comparison operator is expensive, CPU contention is volatile, or if operating on a stream of unknown length, the abstraction may choose poorly. Ultimately, I like the option to choose for myself, but like you, I wouldn't mind having a third option that defers that choice to some heuristic. [1] http://www.techempower.com/blog/2013/03/26/everything-about-java-8/ http://www.techempower.com/blog/2013/03/26/everything-about-...
- leorocky 12y ago> The difference between this and the old Atomics is that here, when a CAS fails due to contention, instead of spinning the CPU, the Adder will store the delta in an internal cell object allocated for that thread. Wow man Java's still all in with it's terrible threading mechanism all the while C# has had async, await and parallelism for years, Go is well past version 1 to great acclaim, node.js and libuv are taking over, and Akka has gained enormous popularity and yet real coroutines in Java aren't even on the horizon. Even python 3 is getting coroutines. Low level threads in Java are so goddamned awful and unavoidable that it makes me want to pull my hair out. And I otherwise love Java. Java would be so awesome with real, native coroutines. Like that should be only thing they should be working on right now. Edit: I'm guessing the people downvoting this have no idea what I'm talking about and don't know what coroutines are. You know I'm starting to think there's maybe an entire generation of Java engineers who have no idea how much easier it is to write concurrent code with other tools and Java has ruined them. I love Java, but expand your horizons a bit.
- eranation 12y agoYou have librarires such as https://github.com/kilim/kilim https://github.com/kilim/kilim or http://docs.paralleluniverse.co/quasar/ http://docs.paralleluniverse.co/quasar/ for Java lightweight threads
- leorocky 12y agoYeah there are some nice libraries, my preference is Akka, but I think Java needs real native coroutines: https://en.wikipedia.org/wiki/Coroutine https://en.wikipedia.org/wiki/Coroutine https://en.wikipedia.org/wiki/Coroutine#Implementations_for_Java https://en.wikipedia.org/wiki/Coroutine#Implementations_for_...
- eranation 12y agoAkka doesn't have native coroutines / lightweight threads, it relies on regular JVM threads. it does reuse them for Actors but it dons't do the same things as Qasar (user level threads via bytecode instrumentation). I'm a big Scala and Akka fan, but thought it's worth noting.
- ChrisAntaki 12y agoSecure random generation is exciting, especially for endpoints.
- mycodebreaks 12y agoWhich companies are running Java 8 already on production?
- ivan_gammel 12y agoFor already having it in production it's too early, but definitely there are companies that have it in near future roadmap. I know couple of them.
- loganekz 12y agoWhy do you think it's too early? My company is running it on production with no issues.
- meddlepal 12y agoMy company will soon
- hyp0 12y agoWouldn't Mandatory<MyType> (or NonNullable<MyType>) be better for Java, since all reference types are nullable (aka optional) already...? Haskell's Maybe monad doesn't meet java's specific needs. It could check for null in its setValue method, at write-time - more useful than discovering it read-time (though I'm not sure it's worth the abstraction).
- nickmain 12y agoPluggable Type Systems: http://docs.oracle.com/javase/tutorial/java/annotations/type_annotations.html http://docs.oracle.com/javase/tutorial/java/annotations/type...
- bad_user 12y agoIn Scala Option[T] works great, as in libraries people stopped using nulls to represent optional values. And it actually works out when enough people are using it. Plus, if you're unsure about a value you receive (whether it's nullable or not), you can always assume the worst and wrap it in an Optional.
- gdi2290 12y agoJava the good parts?
- saryant 12y agoAlready been written, though not updated for Java 8: http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683 http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp...
- terranstyler 12y agoRe Optional<T>: If I get this right, the source code of the signature of many (many!) methods will now be twice the size of before, unless the names of your types and variables were already considerably bigger than "Optional<...>" (10 chars). I hope it's worth this cost.
- wicknicks 12y agoYeah, I hope I am interpreting this the wrong the way. But instead of doing X.getA().getB().getC().getD() we have to X.flatMap(X::getA) .flatMap(X::getB) .map(X::getC) .orElse("UNKNOWN"); //[1] Not sure why this is going to be better? [1] http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html http://www.oracle.com/technetwork/articles/java/java8-option...
- necubi 12y agoThat's not a fair comparison, as the flatMaps are eating nulls (really Optional.empty()s) while the naked calls will throw NPEs. The equivalent code for the first case is: String result = "UNKNOWN"; T a = X.getA(); if (a != null) { T b = a.getB(); if (b != null) { String c = b.getC(); if (c != null) { result = c; } } } Optional (like Scala's Option or Haskell's Maybe) are useful because they force you to reason about "empty" cases. Whereas in typical java code there is no way for the compiler to force to you handle the possibility of nulls (thus leading to NPEs), Wrapping a type in Optional forces you to deal with the case where the result is not present, leading to more correct programs. Plus, it gives you handy tools for dealing with non-present values, like allowing a chain of computation--any step of which may fail--without needing failure checks on every step.