the blog for developers

Want Erlang concurrency but are stuck with Java: 4 Alternatives (+1)

You’ve by now have read a lot about Erlang style concurrency. In Erlang actors are sending messages to inboxes of other actors and react to messages in their own inbox. The advantage of this approach with immutable messages is that you can’t get as easily in a deadlock as with basic Java concurrency with synchronized and threads. A simple ping pong example looks like this:

ping(N, Pong_PID) ->
    Pong_PID ! {ping, self()},
    receive
        pong ->
            io:format("Ping received pong~n", [])
    end,
    ping(N - 1, Pong_PID).

pong() ->
    receive
        finished ->
            io:format("Pong finished~n", []);
        {ping, Ping_PID} ->
            io:format("Pong received ping~n", []),
            Ping_PID ! pong,
            pong()
    end.

Two actors sending each other ping and pong messages with the ! symbol and acting on those with receive. Although there is more to concurrency than Erlang style message passing, as I’ve written lately in a post, for some problems it’s best and easiest to use message passing.

Is Erlang the next Java, but you are stuck with Java and can’t use Erlang style concurrency? Wrong.

There are concurrency solutions for Java which mimic Erlang style concurrency:

Update: “One clarification: ActorFoundry just uses Kilim’s weaver and therefore is not built on top of Kilim.” (see comments, thanks)
Update 2: Another option sugested by Diego Martinelli is to use Functional Java

Sujit Pal has written a comprehensive post comparing the performance of those frameworks with lots of example code:

Over the past few weeks, I’ve been looking at various (Java and Scala based) Actor frameworks. In an attempt to understand the API of these frameworks, I’ve been porting the same toy example consisting of three pipelined Actors responding to a bunch of requests shoved down one end of the pipe. To get a feel for how they compare, performance-wise, to one another, I’ve also been computing wallclock times for various request batch sizes.

And as Kilim has been shown to be as fast as Erlang – I’ve written about the fact here – these Java solutions do indeed look comparable to Erlang in the concurrency space.

What does this mean to your Java Enterprise?

Don’t worry about the multi-core future, Java has plenty to give for your multi-core platforms. And if you’re only stuck to the Java VM but not the Java language, you could go for Scala and gain some functional programming capabilities on top.

Thanks for listening. Hope you’ve learned something. As ever, please do share your thoughts and additional tips in the comments below, or on your own blog (I have trackbacks enabled).

About the author

stephan Stephan Schmidt has been working with internet technologies for the last 20 years. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own. You can find him on Google +

You can leave a Reply here. Of course, you should follow me on twitter here.

You can share this post!
Do you want to tell others about this article? Use the social bookmark icons to submit this artice to the service of your choice. Thanks.

Leave a reply.

Comments

Why not just use Scala (http://scala-lang.org) Actors?

stephan

@John: From the post: “And if you’re only stuck to the Java VM but not the Java language, you could go for Scala and gain some functional programming capabilities on top.”

Robert Virding

I think much of this misses the point: the problem is not to make an actors-like message package (done a few others myself) or immutability (which Java doesn’t have), but it is the close integration/interaction between processes, asynchronous messages, immutability and error handling which is the real strength of Erlang. Things will go wrong, processes will crash and the rest of the system must be able to survive and clean-up afterwards and continue functioning.

You don’t use an actors based model to help on multicores but because it is the best paradigm for many applications. The multicores and distribution you get for free.

Although I hate to quote myself I can’t help it:

http://rvirding.blogspot.com/2008/01/virdings-first-rule-of-programming.html

Rajesh Karmani

One clarification: ActorFoundry just uses Kilim’s weaver and therefore is not built on top of Kilim. It has its own run-time that supports distributed execution of actors, migration, fairness and allows safe message-passing for any complex Serializable object. In terms of model, it abstracts away the mailbox, the control. All these are lacking in Kilim and Scala currently.

Don’t forget RetroWeaver. It lets you use Java 5 language features, and you can compile the 1.5 libraries with it so that they work on 1.4.

stephan

@Robert: “[...] close integration/interaction between processes, asynchronous messages, immutability and error handling which is the real strength of Erlang.”

Yes, could be the case.

1.) “asynchronous messages” I’d say the frameworks can handle this. The annotation based ones are not as nice as using “!” but close to me.

2.) “immutability” Depends on your style, lots of programmers in Java already write immutable code (no getters, excessive use of final etc.), but it’s better if a language supports this – as I’ve said before, all declarations in Java should be final

http://www.codemonkeyism.com/archives/2008/04/22/all-variables-in-java-must-be-final/

3.) “error handling” Currently you’re out of lack for Java and I would use Scala OTP when using the JVM for that.

http://jonasboner.com/2008/12/11/real-world-scala-fault-tolerant-concurrent-asynchronous-components/

Just a note: for “erlang style concurrency” I’m guessing you mean both actors and being able to support a high level of concurrency. For the later you’ll need lightweight threads, so any actor concurrency based on OS threads won’t be sufficient.

Mumbojumbo

Clojure anyone? (www.clojure.org) Runs on the JVM and interops with Java.

stephan

@Steve: Could you be more precise? Both Kilim and Scala seem to perform as good as Erlang does? What am I missing?

I think it’s not a threads problem but a scheduler problem.

@MumboJumbo: I though Clojure had STM for concurrency, not message passing?

@Steve: I am not sure what you mean by ‘lightweight’ threads, but Actors Guild goes to great length to keep the number of threads down – there is no 1:1 mapping between actors and threads.

AG manages all actors which have work, and the number of messages that could be processed simultaneously in the actor. In AG, an actor can be stateless or have stateless messages, or even have ‘multi-threaded’ messages without synchronization guarantees. In those cases, an actor can process more than one thread at a time.
Then, AG calculates the right number of worker threads to process the messages. The exact numberis limited by configuration and the system’s number of cores, as well as the type of message (a message doing IO or even waiting for an external event such as a TCP connection needs less CPU time than a message that computes something).

If you’re interested in this topic and attending CodeMash this week, I’m giving a talk on Actor Concurrency that will cover Erlang, Scala, Kilim and possibly some of the others.

stephan

@Alex: Would like too, currently not in a position to go to conferences sadly.

I wish you good luck with your talk, the topic seems to catch on. It’s a long way though before actor concurrency knowledge is spread enough.

Bjorn Borg

For some reason, actor model does not seem like a natural extension to Java. I am no James Gosling to say whether Java is meant to do this or not. Perhaps should we shift the blame on to the frameworks which have made actor model like an after-thought on Java? These weaving strategy implementations like Kilim, ActorFoundry, Actors Guild etc… have to take some blame for making actor models look very unnatural to Java development – putting a kink in every development step and development tool. The leap of faith with actor models may perhaps never happen until it is made a part of Java platform itself (like how actors implementation is provided as part of the Scala standard library). For now, for die-hards Java nerds, I would suggest that among Java alternatives, Jetlang is the best because it provides a consistent model that does not feel misplaced or unnatural in the context of Java.

Bjorn Borg

Kilim in my judgment is an attempt to misuse the purposes of a University in coming up with an offering to gain appeal with Java corporate world in the guise of academic research work. Hundreds of successful Java frameworks have been written during week-ends by great people through open source initiatives. Kilim can come no way close to them in terms of acceptance from the Java community. But unlike Kilim, none of them have got a PhD because they were willing to play by the moral rules of the game than go for fringe gains. You don’t need the paraphernalia of a University (professors, library, state grants …) to write a Java framework eh! Hope Universities see through this, if not they will be rendered inconsequential. For heaven’s sake, may Universities focus only on works which have larger impact on the society, bring real futuristic technologies that would make our generation proud!

[...] actor frameworks for java [...]

Leave a Reply

What people wrote somewhere else:

Additional comments powered by BackType

Guide to CodeMonkeyism

Over the last 4 years I wrote many articles on this blog. To make it easier for you to find the relevant ones, I've organized them into topics.

Top 10

6 reasons why my VC funded startup did fail

Go Ahead: Next Generation Java Programming Style

Java Interview questions: Write a String Reverser

The dark side of NoSQL

7 Bad Signs not to Work for a Software Company or Startup

Is Java dead?

Scala vs. Clojure

Never, never, never use String in Java

No future for functional programming in 2008 – Scala, F# and Nu

Clojure vs Scala, Part 2

Java Developer

Is Java Dead?

Go Ahead: Next Generation Java Programming Style

Be careful with magical code

All variables in Java must be final

Never, never, never use String in Java

Bending Java: More readable code with methods that do nothing?

NoSQL Guy

NoSQL: The Dawn of Polyglot Persistence

The dark side of NoSQL

Essential storage tradeoff: Simple Reads vs. Simple Writes

Sharding destroys the goals of your relational database

The unholy legacy of databases

Startup/CTO

Development Dream Teams

6 reasons why my VC funded startup did fail

American vs. European style of Software Development

12 Things to Reduce Your Lead Time and Time to Market

The high cost of overhead when working in parallel

Essential storage tradeoff: Simple Reads vs. Simple Writes

Job Seeker

Another Good (Java) Interview Question

7 Bad Signs not to Work for a Software Company or Startup

Java Interview questions: Write a String Reverser (and use Recursion!)

Java Interview questions: Multiple Inheritance

As a Manager: What I value in developers

Top 10 Tips (+1) to Get a Pay Raise

Agilist

What Developers Need to Know About Agile

5 Practices Better to Change in Your Scrum Implementation

Scrum is not about engineering practices

ScrumMaster and ZenMaster: The joke of certification

What is Trans-Scrum?