226 points · by dafnap · 12y ago · 163 comments
Java devs-- you seriously owe it to yourself to spend the time investigating and ramping up onto Scala and Play. This is where the future of Java web app development is being driven from, by Typesafe and the Play / Spray /Akka open source developers. You do yourself a great disservice by sticking with Spring, Hibernate, JBoss, and the old standbys.
Please enough of that, especially coming from the Scala community. Let's act as professionals and judge tools on their merits instead of instigating flame wars.
Second, I'm doing both (web Java at work, web Scala on my spare time) and in my experience, there is really no clear winner. What's especially interesting is that I can find about the same number of positive things to say about the Scala tool stack (Scala/Typesafe platform/Akka/Play) as I can say negative things about each of them. Every time I'm happy about something in the Scala world, I find something I'm not happy with that counter balances it (tooling, slowness of template recompilation, unprovedness of the actor model, Play's arguable step backward in the v2 compared to v1, etc...).
Java is impossibly verbose and has a very limited type system compared to Scala but man... do I develop things quickly with it. There is close to zero friction to get from nothing to something workable, maintainable and fast. And the tooling is top notch, the environment and compilers are super stable, and Java 8 is numbing a lot of the pain I used to feel. In contrast, I feel that I'm often fighting against the Scala compiler whenever I write Scala code. It feels nice in the end to see how concise and neat the code looks compared to Java, but I'm never really convinced the pain was worth it.
So, back to your original point: I've tried (and continue to experiment with) all these "new" technologies that Scala is claiming to bring to the table, and so far, I'm unconvinced that they are a clear improvement over what we currently use in the Java world.
And given that Scala continues to be a marginal language on the JVM, I don't think I'm the only one doubting that Scala represents the future.
The real benefits of Play and Akka become apparent when a third-party service you send API calls to starts acting flaky. Or when your web service that you offer to clients is suddenly being hit by an iPhone game that just got purchased by a million people. Or when that nasty little bug that winds up throwing an exception from time to time rears its head all of a sudden. Play and Akka give you a resilience that is very hard to come by in the Java world.
Typesafe's home page has, in giant type, "Applications are becoming Reactive" and they are absolutely spot f'ing on. Writing blocking code, waiting on threads, assuming you're running on one JVM, these things are great and all, and very easy to do because all of those templates are built into IntelliJ and you just have to click a few buttons to get all that, but wow, the performance difference once you get into the Play world is just frighteningly good.
Of course there are Java developers who can kick ass with Spring, Hibernate, Servlet containers, and war deployments, but all of these tools are huge, bloated, and starting to show their age. Modern frameworks like Play make things simpler for those of us who don't have +7 year JEE experience with Spring and Hibernate.
There, fixed that for ya.
I agree with the Java vs Scala poster. And unlike him, I have a 30,000 line scala production project under my belt. Everything he says is true, and then some. Ever split up a file into chunks because intellij can't edit it effectively?
Yeah, didn't think so. (Just telling like it is)
Interestingly, the biggest thing I wish I had when writing Java is algebraic data types and pattern matching. A few years ago I would have said it was lambda, but having sum types would make expressing many things so much easier.
We rewrote these applications using JAX-RS (RESTEasy) and they were much simpler, easier to maintain, without API breakage in new framework versions. It just a bunch of methods with annotations. XML and JSON serialization is automatic (via JAXB and Jackson). And you can use the same lightweight ORM as Play (Ebean), since it's an external project.
Well-thought out, mature technology is often better for getting work done than the hype of the day.
Play 1 was almost perfect. Really hope someone would fork Play 1 and continue with it.
This is, imho, what makes Play so fantastic. That you can have def index = Action { hardComputation() } for blocking code, and change it to def index = Action.async { Future { hardComputation() } } and you have magically changed your application to be asynchronous through the request-as-actor paradigm of Play. Play makes it easy to write async code. Play makes it way easier to control configuration for things like thread pools, dispatchers, and the like vs. Jetty. The performance of the nonblocking async code is incredible, and winds up saving a ton of money and developer time.
Async is only beneficial in terms of IO.
Given the amount of money you get with them, doing consulting in Germany, I think they will stay around for quite a while.
Also, Spring is not that bad, though sometimes I have hard time to understand some of the initialization/runtime problems. Hibernate and JBoss I rather skip, and use Tomcat and Dalesbred for relational data access.
I think Play / Spray and Akka are great but let's differentiate between the language and the framework.
You can write Play / Akka with Java (they added Java 8 support recently) and you can write Spring / Java EE with Scala (I do that all the time and it's working great)
More than that, I have mixed Java / Scala projects and it works like a charm (once you configure maven / gradle correctly that is)
The "new" Spring versions are nothing like it used to be. Also the new Java EE ones. no XML configuration files, all convention over configuration. And I sometimes prefer a @GET + @Path or @RequestMapping annotation over concatenating routes with ~ like they have in Spray.
It's just a matter of preference and personal taste, but let's separate the language discussion with the framework / ecosystem discussion, they are not the same.
It'd be nice if we could also write Gradle with Scala, or some other decent JVM language.
Those technologies have stayed on, while other trends have come and and go.
I put my money on TypeSafe.
Pivotal still (05/2014) doesn't have Java8 support for some of it's frameworks (grails https://jira.grails.org/browse/GRAILS-11063 ). TypeSafe pre-released versions of Play that take full advantage of Java8 features.
Given that if you need to run a Java 1.4.2 app on top of JBoss (or Glassfish!) then the types of technologies that these two companies are pushing are solving problems in a different domain.
And arguably the PermGen change in Java8 would benefit Grails/Groovy the most.
While I agree with you about the others 'json manipulation' is not an area that Play can even be compared to Jersey (Jackson). Jersey transparently converts the request body to the required input type whereas with Play you still have to un-marshal the body while taking care of errors (admiddently that can be 'hidden' away using Action composition but still is work that the developer has to worry about). With Jersey its magic that just works.
The pleasant, compositional interaction borne of Scala's syntactical flexibility is why Play's wonderful to use (and Akka as the backend is largely behind-the-scenes). I used to be a detractor early in Play2 because of some large-scale-unfriendly decisions, but they've pretty much all been fixed.
For Java web development, it is worth re-considering Spring Boot though * (http://projects.spring.io/spring-boot/)
Spring MVC and Data (et al) powered entirely by annotations, and (e.g.) Thymeleaf for templating, can lead to some fairly powerful yet concise apps.
We just started using this where I work, and it's a great step forward compared to old style, XML driven Spring MVC and Hibernate.
Also Spring Boot does bring quite a lot of support for REST, via RestTemplate/RestOperations, along with support for consuming and producing JSON and/or XML at the controller levels.
* Edit: I say re-considering since the article only briefly mentions it.
Modern JavaEE isn't nearly as heavy as the article seems to think ... but I can't argue with the article's underlying pragmatism. Use the simplest set of tools that accomplish the task!
The Spring solution to this problem was always my favorite part of their stack: JDBC template removed most of the error prone boilerplate from JDBC, adds a couple of features, and still lets you write SQL directly, which is probably what you should be doing in almost all the cases where a relational database becomes valuable.
I can't wait for shops to start to use Java 8. The removal of so much boilerplate when trying to build functional interfaces should make the Java toolsets move forward very quickly.
I never cared for the library until I realized I'm spending a lot of time on the developer's blog; he is prolific and very knowledgeable about everything database and java. Was sold on it soon after.
http://huherto.github.io/springyRecords/goals/
Also, this fellow HNer has been experimenting with Java 8 features. Pretty cool. https://github.com/benjiman/benjiql
I suspect that task size has to be smaller than the typical bit of web processing code for context switching overhead to really dominate, or even be expensive enough to matter. That says as much about how expensive common tools and frameworks are as it does about the cost of context switching.
EDIT: scratch the last statement about Go using OS threads for goroutines. I was thinking of something else.
Sometimes on Linux systems, even allocating a large stack size doesn't actually consume that as physical memory. Malloc might give you the memory block, but until you actually make function calls or allocate data on the stack, it might not consume the memory.
Now, fibers are not perfect: their main shortcoming is integration with legacy code. The optimal approach is scheduler activations, or "user assisted" kernel scheduling.
On the other hand, Go does use green threads, and the main developers of Go are by no means naive. So maybe green threads do have some benefit, but only when implemented in something higher-level than libc and pthread.
https://news.ycombinator.com/item?id=6977177
BTW, I wonder if Paul Turner's work on fibers will change this equation if/when it makes it into the production kernel.
https://www.youtube.com/watch?v=KXuZi9aeGTw
Google has had very promising initial results with it.
EDIT: So I guess we should run more big multi-threaded server apps with musl and see what breaks.
If you are in a million thread scenario it is usually because most of them are idle and retaining state for some eventual activity. That also tends to mean that they are long lived.
It would be interesting to do this for native threads at the kernel level: it's very similar to swapping, except for stack data you could just throw the data away if you could figure out that it was indeed dead.
It's true that app servers were originally conceived as a way of hosting multiple apps in a single JVM, but it quickly became apparent that this was a terrible idea, and nobody does it. You run one instance of the app server per app. The app server is really just a great big bundle of useful libraries and a web framework.
Anyone interested in modern JVM web development I would still advise to invest time in learning Scala (or Clojure). They can work with your legacy code and libraries, but my productivity and general joy in programming shot through the roof when I started using Scala.
That was exactly my experience. Maintaining Java code from time to time makes me realise just how big the difference is.
It's a questionable framework mashed together with a poorly though out messaging system.
I would rather use Spring Integration, Quasar, or Akka.
Classloader per verticle type makes dependency injection painful. "I don't know what a Spring "ApplicationContext" is" -- Tim Fox
Uses multiple classloaders so you can "run multiple versions of the same module at the same time". Not something I have ever done or would do.
Uses Hazelcast for clustering but uses tons of classloaders so using anything other than simple types in Hazelcast is hard and inefficient.
Message bus is tightly coupled to application cluster through Hazelcast.
Messaging is missing the most useful features of AMQP like wildcard topics and queues. Only possible to do very basic message routing. Many messages have to be sent multiple times to mimic advanced routing.
Dividing everything into 'verticles' encourages use of callbacks for everything. This increases code size and complexity which increases the need for testing. 'Callback hell'
Encourages polyglot programming.
Writing Vertx apps with Groovy makes me feel like I could add a whole chapter to 'How to Write Unmaintainable Code'.
for {
user <- asyncGetUser(1)
company <- asyncGeCompany(user.companyid)
longresult <- asyncProcess(company.getSomething)
} yield longresultIt can be a problem. In Akka actors, referencing sender() from a future will be unpredictable because sender() could've changed in the mean time.
I think there are three strong solutions which address this problem:
1) Immutable state. Solves this problem completely but accidental capture remains an issue.
2) Hiding mutable state within actors. I hesitate to present this as a general solution though since it really requires going all-in with actors (I don't consider that to be a bad thing, necessarily).
3) Projects like Scala Spores [1] aim to tackle this at the compiler by capturing mutable references and executing async closures in an immutable environment and prohibiting accidental capturing. IOW, turning accidental capture into a compiler error. I'm excited about this one.
[1] https://speakerdeck.com/heathermiller/spores-distributable-f...
It's also somewhat unavoidable when you're dealing IO, unless you stick to .pipeTo(self)
user = getUser(1)
company = getCompany(user.companyId)
longresult = process(company.getSomething)
is a) simpler (because that's what your normal code looks like), b) performs exactly the same (as fibers basically do the same thing, only transparently), and c) retains context (like ThreadLocal variables).So if that was the only way, I'd say, fine. But once you have lightweight threads, they are always preferred (even Scala now has its own poor-man's lightweight threads in the form of async/await).
Actually, no. My code will always look like the for comprehension be it async or not, because my 'get' methods will always return an Either, Option or some other monadic context to represent the computation succeeding or not.
> performs exactly the same (as fibers basically do the same thing, only transparently),
Yes, I agree.
> c) retains context (like ThreadLocal variables).
Threadlocal variables are almost always code smell. If you find yourself using them, there is almost certainly a better way of accomplishing the same thing.
I don't see how having a Fork/Join threadpool that 'powers' the futures would be any slower than lightweight threads either.
Maybe it's just been a long time since I had to deal with Java-land, but you need to know about so many different things just to get off the ground. Granted, this may be easier with newer frameworks, but still.
I think that's probably true of just about any mature environment these days, isn't it?
Nobody wants it to be true. You make something new, thinking, this time i'll do it right, it'll be so simple, easy to get going with. And it is at first. Then you add stuff to deal with all the things that turned out to be pain points, all the edge cases and use cases that someone had that seemed reasonable after all, before you know it, it's a monster again.
To get off the ground with Rails 3/4, you sure need to know a lot. That wasn't neccesarily true in Rails 1/2 when some of us got started, and we were able to learn the new stuff gradually as it was added in, but to get started from scratch, let's say you don't even know ruby very well, oy, it's a lot now.
And why? Because we want a mature environment to do a bunch of things for us, so that we don't have to (badly) re-implement everything. But the price of that is, we have to learn how to get the framework to do those things for us.
And, personally, the problems don't end there--I think I'd quit programming before going back to any Java-based hat-on-top-of-JDBC. Scala's Anorm/Slick have given me enough of the "there's a better way" to make going back really unpalatable.
For what it's worth, Akka is even more relevant to what I'm doing.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
Of course, you still need to know how Python Does Things, and The Thousand Ways To Deploy An App, and Package Management and so on, but for this trivial example it's a lot more conceptually lean than the semi-equivalent offered above. I don't need to know about `Bootstrap<Configuration>` or a `JModernConfiguration`.It's fair to point out that there will be a corresponding text file or option somewhere else, but…
public class HelloWorld { public static void main(String[] args) {
get("/hello", (request, response) -> {
return "Hello World!";
});
}
}You import some stuff... check. You create an instance... check. You define a route... check. You define a method to implement the route... check. You return a String... well the example returns a map, and converts it to JSON. You start the app in a main method... check.
Sure the java is a little more wordy and there are some extra params which are not used (the IDE would fill those in automatically when you implement the interface), but the complexity is the just same as far as I can see.
require 'sinatra'
get '/' do
"Hello World!"
endBlocking IO cannot have predictable latency under load at very least, you are left at the mercy of OS thread scheduler. Due to various reasons (e.g. mutator threads should not block GC and compiler ones) thread priorities are honored.
I'd argue that a well written NIO (and virtually there are no good open source NIO impl) will beat flat out any blocking. NIO is both faster and offers better/predictable latency under load.
Most impl. use heap ByteBuffer, then parsing requires state machines and often they are simplified by copying the buffers. The blocking IO doesn't really need a state machine as the stack serves that purpose. Then there is some reactive alike pattern (submitting tasks to an ExecutorService) that costs some more latency. Certainly, it's easier to work with and reason about, yet the more hand-outs there are the worse the performance/latency is. There are minor issues like the choice of a good queue. It is an important one as java lacks MultiProducer/SingleConsumer queues out of the box, or even single producer/single consumer. Java does have MP/MC queues (CLQ is an outstanding one) but one has to pay some extra price (incl. false sharing sometimes) to use them.
Ultimately the blocking IO cannot be "faster" than NIO per se since under the hood it uses poll(2)[0] with one socket. Before that it copies the java byte[] to a new location - for smaller byte[] it's the stack. Technically one can blow up the JVM if the stack is very tiny while entering socket.getOutputStream().write(byte[])
Lastly Selector.wakeup() has a stupid issue that involves entering a synchronized block each time even if there is an outstanding wake-up request already. Wakeup requests are implemented via pipes on linux (and a socket pair on Windows) that requires kernel mode switch. During the wakeup all the threads attempting to carry the task block on that very selector for no real reason. It can be played around with a CAS, so only one thread actually enters the monitor.
I will repeat myself blocking IO doesn't have predictable latency and cannot be enforced. In the end it's all about the latency as bandwidth can be bought, more machines deployed but you can't buy latency.
[0]http://linux.die.net/man/2/poll
Some internal stuff on heap vs direct buffer: http://stackoverflow.com/a/11004231
These tests were a particular kind of network traffic, and were testing for max throughput across many connections. Minimizing latency, smaller message sizes, and/or fewer connections can make the decision to use NIO vs standard IO libraries come down in different places. (Not to mention that you cannot program the standard IO libraries in a no alloc form).
DBObject r = collection.find(query);
It blocks while getting the results of the query. If I do something like this: for (int x=0; x < 100000; x++) {
new Thread(() -> DBObject r = collection.find(query))).start();
}
it's going to start 100,000 threads and freeze my computer. However, with Fibers I can do: for (int x=0; x < 100000; x++) {
new Fiber(() -> DBObject r = collection.find(query))).start();
}
and it will work fine since these are lightweight threads (like Go goroutines). I guess my main question is, can I use arbitrary unmodified synchronous code like this to run in Fibers or would the library have to be modified to support it? In this case, would someone have to update MongoDB library to add support for Fibers?If library provides asynchronous APIs, it would yield great performance when integrated with Quasar fibers. If not (like JDBC), it would work as well as it does on regular threads, but won't interfere with all the other great stuff fibers can do.
The opposite canonical example being a static, small-file web server. Short connections. How many files can you serve per second?
Java is not my main language, but I liked the Advanced Topic: Blocking vs Non-blocking section and in general have been following Parallel Universe technology stack.
If anyone is interested more in the async vs actors, there is a nice new podcast with Ron Pressler, Fred Hebert (Learn You Some Erlang For Great Good author), Kevin Hamond and Zachary Kessin
http://mostlyerlang.com/2014/05/15/037-parellel-universe-wit...
There is a discussion about concurrency, how Quasar works underneath (hint: there is an interesting bytecode transform that takes place during loading), shared state, Erlang, Clojure and Datomic. Anyway, highly recommend.
public class WebAppConfig extends ResourceConfig {
private final String[] mimeTypes;
public WebAppConfig() throws IOException {
//load static resource from htdocs dir
Collection<File> files = FileUtils.listFiles(new File("./htdocs"), null, true);
ArrayList<String> mimeTypeList = new ArrayList<String>();
for (File file : files) {
final byte[] contents = FileUtils.readFileToByteArray(file);
Resource.Builder resourceBuilder = Resource.builder();
resourceBuilder.path(file.getAbsolutePath().split("/htdocs/")[1]);
final ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("GET");
String mimeType = Files.probeContentType(Paths.get(file.toURI()));
if (!mimeTypeList.contains(mimeType)) {
mimeTypeList.add(mimeType);
}
methodBuilder.produces(mimeType)
.handledBy(new Inflector<ContainerRequestContext, byte[]>() {
@Override
public byte[] apply(ContainerRequestContext req) {
return contents;
}
});
registerResources(resourceBuilder.build());
}
//load dynamic resources implementing interface Webpage
register(MultiPartFeature.class);
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forJavaClassPath())
.filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.example.mycompany"))));
Set<Class<? extends Webpage>> webpageClasses = reflections.getSubTypesOf(Webpage.class);
for (Class<? extends Webpage> webpageClass : webpageClasses) {
registerResources(Resource.builder(webpageClass).build());
}
mimeTypes = mimeTypeList.toArray(new String[0]);
}
public String[] mimeTypes() {
return mimeTypes;
}
}
...
public synchronized void start() throws Exception {
WebAppConfig config = new WebAppConfig();
HttpServer httpServer =
GrizzlyHttpServerFactory.createHttpServer(URL, config, false);
CompressionConfig compressionConfig =
httpServer.getListener("grizzly").getCompressionConfig();
compressionConfig.setCompressionMode(CompressionConfig.CompressionMode.ON);
compressionConfig.setCompressionMinSize(1);
compressionConfig.setCompressableMimeTypes(config.mimeTypes());
httpServer.start();
wait();
}With SDR, you have an @Entity, and a @Repository for that entity, and SDR handles the whole HTTP part, i.e. you don't need to write a @Controller to expose the repository.
Just wondering if Jersey has anything similar.
IMO I would rather use a single threaded server and manage synchronicity explicitly with callbacks, composable promises, comprehensions, monads, and "other functional shenanigans" vs having to sync shared state across threads and manage thread pools.