Java 8: New features in ConcurrentHashMap
deadcoderising.com
deadcoderising.com
.NET core is still very immature, we had to back out every time we tried to use it in production. Maybe in a few years it will be good.
Java on the other hand has support for many IDE's, package managers, web servers, JVM's, OS's. You can swap out pretty much everything, no vendor lock in issues at all. The open source community is far stronger as well. So many times I wanted to use a cool database and found out there's no official C# client
I personally really like Java and I've used a ton of languages over the years. Not a perfect design but it's hard to think of any big downsides. The syntax is annoying at times but once you learn to use the IDE to poop out boilerplate it's not an issue
Java is a compiled language.
A really important aspect of using an intermediate language like Java, .NET but also LLVM does is that it reduces the amount of required code. If you have M languages each targeting N different platforms, then you need M * N traditional compilers. If you first compile to a common intermediate language and then from there to the targeted platform, then you only need M + N compilers.
Do you have examples (incl. measurements) for optimizations actually performed by a Java JIT compiler, which an ahead-of-time compiler can't perform due to a lack of runtime info? It is my understanding that those analyses and transformations which eke out the last few percentage points are so expensive that they're infeasible to do at runtime.
I wanted to cite "Improving Java Performance Using Dynamic Method Migration", Lattanzi 2004, but the site hosting the paper isn't loading at the moment.
[1] http://www.oracle.com/technetwork/java/whitepaper-135217.htm...
[2] https://www.microsoft.com/en-us/research/publication/spur-a-...
With JIT you can set the size when you create the object, and if JVM knows that value can't change it will pull out all the branches for different sizes and run only the one for selected size.
There's no way to know which sizes will be selected at compile time if the lists can be dynamically created, so a static compiler can never pull out all the checks the list size.
This is a simple example but the JIT is very smart and makes a big speed difference in practice. It's the main reason Java is faster than C in some benchmarks
As an example of what they can do, take de-virtualisation. Virtual method calls are expensive. Java method calls are virtual by default. The JVM profiles method calls and analyses the class hierarchy to discover which ones can be de-virtualised. That's a big win. C# requires programmers to manually specify which methods are virtual because .NET doesn't use profile-guided JIT compilation. In some cases (admittedly I've only seen artificial examples) this optimisation is so powerful you can write Java programs that completely trash C++ programs, e.g. a program that uses a command line switch to pick a subclass of a virtual base class and then runs method calls on that object in a tight loop. Java will devirtualise the call based on the observation that only one target is ever used, then inline it, then do loop opts on the inlined version.
in my mind: interpreted = why would you ever use a language like this? VM = fast, safe, but going to use a lot of memory machine code = fastest, low level HW access, usually unsafe
This distinction doesn't make much sense in 2017: most languages are blends of all these things with technologies like VM's, JIT, Ahead-of-time compilation, etc...
Then there's interpreted code which has worked the same way for forever
This whole setup helped me develop surprisingly large number of useful tools and apps which proved successful enough that snippets of my code and pattern are copied in proper 'enterprise class' projects at our company.
Forcing all objects to be heap allocated which makes things like Optional introduce even more memory indirection because thrashing your cache is totally fine
No primitives in generics which therefore means no primitives in containers
Which then leads to the fun of autoboxing so that way your bools can be true, false, or null!
Yes it is better than a lot of things, but it is also a super low standard. It get things done if you are ready to deal with all its problem... But it is still the child of its history, and its shows.
The security issues were mostly in Java applets. The language itself is pretty damn secure. I can't remember the last time I saw a web exploitable issue in the JVM.
There's still a lot of innovation going on in the Java community you just don't hear about it.
And i was not comparing Java to C# or Python here, but that is probably due to my personal background, which is more with OCaml, Erlang, C, Rust and co.
- Everything Java does, C# does as good or better. In general for everything in Java you could easily find a better way to do it.
- Java has lots of warts, many to have the language be backwards-compatible. (switch-case, enums, UTF-16 encoding, generics, null, difference between objects and basic types,...)
- Java is tied to old technologies. There are no standard JSON libraries, however even XSLT is included in java se.
- You need to use Java with an IDE. Eclipse is horrible to use (even scrolling lags here) and IntelliJ costs money.
Still java is a mature and solid language. There is just nothing to hype about it.
As others have said the open source community for Java is still leaps ahead of C#. It's not often you find a library which doesn't have a Java connector/implementation. For C# on the other hand you tend to be much more limited in your options.
I guess this used to be a lot due to the platform dependence of C# (and probably still is). Hopefully .Net Core can help with that, but it's not ready for prime time yet IMO.
- Every language has switch-case and enums? I don't get what you're trying to say there.
- Generics are fine?
- Every language supports null on objects?
- Nearly every language treats null and primitive types differently for performance reasons
- Java has three popular JSON parsers and they're all faster than .NET's builtin serialization. To get similar performance you need to use Newtonsoft which isn't builtin to C# either :).
- You don't need an IDE, it's just stupid to develop without one because they're so helpful. Nothing is stopping you from running javac on the command line.
You can't do a LOT of things java can do in C# because third party library support pales in comparison. A lot of databases and open source software don't have c# clients. If you're dealing with big data or ML you'll find almost nothing in C# land.
I feel like you haven't used Java in a long time. Things are much better than Java 6 days
- Java has the same horrible switch case with the error prone break as C. If you want exhaustive matching on enums you will end up with a useless default case. If you ever worked with a programming language with pattern matching you will feel the pain.
- This might be a bit opinionated but I think enums are not enough. Sum types/tagged unions/variant types/disjoint unions/whatever you like to call them are pretty useful.
- Generics in Java are highly limited. Part of that is because generics were added as an afterthought and are implemented using type erasure. Both functional programming languages like Haskell or imperative programming languages like C++ or Rust offer more powerful generics that can sometimes help abstract things more elegant.
- The problem is that all objects are nullable by default and you cannot specify that e.g. parameters or results are never null. This leads to boilerplate null checking and missing handling of null cases. Everybody that touched java probably saw quite some amounts of NullPointerExceptions. Kotlin for instance offers types that by default cannot be null, with TypeScript this exists if you turn on an option of the compiler.
- You can offer pretty much everything you offer for objects also for primitive types. In fact, this is what Project Valhalla tries with value types and specialisation.
- My comment on IDEs was more about the need to use an IDE being bigger with Java than for instance C, while eclipse is often annoying. I am using eclipse daily currently because I work on some Java code for my Master's thesis.
Really, why ?
I can't imagine working without an ide for any language. Back in the dark days I did html/javascript in notepad.
It's really true. It's so refreshing switching from Java to C#. I mean, they're both statically-typed-OOP-garbage-collected-bullshit-enterprise languages, but if you're gonna go with one of those, C# is far more pleasant than Java.
With CHM and computeIfAbsent, it's easy to write lazy loading "by key" (i.e. simple caches). Prior to Java 8, I had to resort to Guava's LoadingCache.
computeIfAbsent() allows you to pass in a lambda (a Function really) which will only be called if necessary, thus avoiding a potentially unnecessary Object creation/etc.
E.g. if you are coming from modern C++ use and you are comfortable with templates, you might be disappointed with giving up all that power in Java.
Well, from that point of view, static typing in general is just syntactic sugar. In fact type erasure is one of the best things going for Java, because they haven't screwed the runtime for other languages (e.g. Scala, JRuby, Clojure). Ironically it is the JVM that turned out to be the multi-language VM, with the CLR having only languages that have basically C#'s type system.
No, the problem with Java generics is that covariance / contravariance rules are "call site", specified with wildcards, which are awkward and hard to reason about, versus "declaration site" in Scala and C#.
Scala also has higher kinded types, one of the few languages actually. In combination with making it possible to encode type-classes, by means of plain traits along with implicits, you can express Haskell's powerful abstractions in Scala. You don't see libraries like Cats or Scalaz in other languages like Java or C# or F# for that matter, because they can't be expressed in languages without higher kinded types.
http://openjdk.java.net/jeps/300
And they're also adding type specialisation and reified generics as part of the value types work, somewhat similar to what's available in C++ (but a bit less crazy).
Specialization for value types != reification and from what I understood from their proposal they are not introducing reification, for one because they still have backwards compatibility concerns, but also because they don't want to screw other languages. I hope those plans haven't changed.
Edit: Where did the basic docs on type bounds in Scala go?
I know even use it in personal projects in place of JCL wherever I can.
- Built in types (immutable persistent collections, Try, etc). You can get these in Java with http://www.javaslang.io/ but it's a relatively new library.
- A concise syntax for creating value types without using something like Lombok.
- Mature libraries (ScalaZ, Monocle, shapeless, etc) for people interested in more sophisticated functional patterns.
Immediately off the type of my head: case classes, pattern matching, and maybe scala.js.
Pretty sure scala still has the upper hand in total loc vs corresponding java.
That said I enjoy Java enough so its no biggie I can't find scala positions worth looking into.
I currently use Java for work and I cry a little inside every time I see big hashCode() methods, toString() methods and a chain of getXXX()/setXXX() methods when I know that a simple case class statement would have been all that was needed.
final class Data() {
final int id;
final String name;
public Data(int id, String name) {
this.id = id;
this.name = name;
}
}
No need for getter/setter.
Still not as good as the scala one tought, but probably a little bit faster since it does not use accessor methods.P.S.: I'm a scala user.
case class Data(id: Int, name: String)
and comes with all the other things merb mentioned. And it's unlikely to be any slower in practice since the JIT can inline the access (not that method calls are ever likely to be a noticeable overhead anyway).I'm sure others have said it, but type aliases can't be done in java. For instance this is useful for seeing 'PersonId' instead of 'String'. More semantically meaningful names. You can emulate it in java, but you incur a runtime cost and have to write a wrapper class.
Another interesting feature is value types. There is work in java to support this, but it's java 10 at the earliest (see https://en.wikipedia.org/wiki/Project_Valhalla_(Java_languag...). Since scala runs on the JVM which doesn't support value types there are cases where it has to allocate an object. (see http://docs.scala-lang.org/overviews/core/value-classes.html)
And Scala itself is evolving, the new compiler, Dotty, brings a host of new features[1] including union types, implicit functions, trait parameters, etc., all while improving compilation speeds and streamlining compiler internals. Add Scala Meta (overhauls old macro system), Scala Native joining Scala.js as Scala alt-JVM targets, and you have Java 28 ;)
Saying that, Scala will likely remain a niche language, Java is king, slow and steady wins the race in the enterprise.
Kotlin marketing != reality, it seems.
It caught up a lot, but it's still a jump like IE7 was from IE6 compared to the Firefox of Scala. A hell of a lot better, but still lacking.
Scala is one of the very few languages that makes functional programming comfortable and is among the handful able to do higher kinded polymorphism and to encode type classes. You can probably count with one hand the number of languages in which you can express Haskell's powerful FP abstractions and Scala is one of them.
You cannot express libraries such as those in Typelevel (Cats, Shapeless, etc) or Scalaz in languages like Java, C# or F# for that matter. The only other comparable languages in expressivity, maturity and potential are OCaml and Haskell, with OCaml being very similar in spirit, but less popular (and F# is no OCaml ;)).
Of course, you will never feel this unless you actually start using the language, getting past the initial hello world and Javaisms. This problem was coined by Paul Graham as the "blub paradox": you can only notice inferior languages, abstractions and paradigms to what you currently know, but you can't easily notice superior ones, unless you make an effort to learn more. The great thing about Scala is that it allows a gradual migration and although this expressivity can be seen as a weakness, it's also why Scala is probably the most popular FP language.
This problem was coined by Paul Graham as the "blub paradox":
you can only notice inferior languages, abstractions and
paradigms to what you currently know, but you can't easily
notice superior ones, unless you make an effort to learn more.Whereas writing a performant concurrent "computeIfAbsent" is extremely non-trivial and if you try to do it yourself, you have a high chance of getting it wrong or slow.
Therefore, CHM "computeIfAbsent" is new and exciting, and Map "computeIfAbsent" is "could care less".
Worth noting that's not actually the HashMap implementation.
if (!map.containsKey(key)) {
V value = compute(key);
V existing = map.putIfAbsent(key, value);
if (existing != null) {
// someone else won the race
}
}http://winterbe.com/posts/2015/04/07/java8-concurrency-tutor...
Talks about some other useful topics as well. It's probably not news to everyone, but the third part covers a fair bit of CM/CHM.
I'm thinking of:
forEach(long parallelismThreshold, BiConsumer<? super K,? super V> action)
forEach(long parallelismThreshold, BiFunction<? super K,? super V,? extends U> transformer, Consumer<? super U> action)
I get why we have function, bifunction, consumer, biconsumer, and all that. What I don't understand is why we have a special method for applying a function before passing to the consumer. It seems like the minor convenience in terms of syntax is outweighed by the proliferation of method signatures.There's also one annoyance that neither function composition nor extra method signatures solve, which is boxing primitives. The transformer has to return an object, and the action has to accept one, so the example forEach(4, List::size, ...) will generate a bunch of boxed integers. Hopefully the JIT will notice this and try to elide the allocations, but I don't know how much you can trust the JIT to figure that out. The best thing to do is to manually compose the operations yourself, but that isn't always possible or convenient.
When does manual composition not work well? The article's examples seem easy enough:
map.forEach(1, (k, v) -> "There is " + v.size() + " articles about " + k, System.out::println);
map.forEach(1, (k, v) -> System.out.println("There is " + v.size() + " articles about " + k));Manual composition can get ugly if the argument is used multiple times, especially if the function is non trivial. Say something like
map.forEach(1, Expensive::func, x -> x * x)
which would naively manually compose to map.forEach(1, (k, v) -> Expensive.func(k, v) * Expensive.func(k, v))
which is going to be less efficient, doubly bad if that function has side effects, and noisy on top of it. You could assign the value to a local variable inside the lambda, which gives you map.forEach(1, (k, v) -> { int x = Expensive.func(k, v); return x * x; })
which fixes the efficiency and correctness problems, but is a bit too verbose for me. There's probably other situations, that was just the first one I thought of.Honestly, though, it all comes down to taste and the situation. I personally would use manual composition excepting circumstances like my example above.
So while it's been out for some time, a lot of enterprise code bases are only just now starting to move to Java 8, and developers are only now really getting their teeth into these sorts of features.
Also, Java 8 was a pretty huge release. Even experienced developers are no doubt discovering little new interesting features and tricks all the time.
newer, trendier languages like Python, Ruby or C++? ;)
edit: now with parameters and custom literals
It can take a while to move to new major language versions, especially when they have major new syntax changes; toolchains and IDEs take a long time to mature. Java 4 -> was huge, 5->6 was very minor, 6->7 medium (string switch statements, try-with-resources, and multi-catch), but 7->8 is another huge change. My guess is that Java 9 will be accepted much quicker than 8, since its changes are not going to be nearly as big as 8.
And even now it still does it do so... unless you do it on purpose but implement properly j.u.Comparable.
Maybe there are optimizations, but why would you have a custom signature to add a transformer (really it's just a map()) to forEach(), when you would normally just .map().forEach()?
Might have to do with the parallelism. With the transformer in the forEach call, the transformer will (presumably) be on the same thread as the consumer.
(That's just a guess--I haven't actually looked at code)
> .search()
Why didn't they name the function "filter", like everyone else does?