Erlang processes vs. Java threads

By: on September 10, 2006

Earlier today I ran a simple test of Erlang’s process creation and teardown code, resulting in a rough figure of 350,000 process creations and teardowns per second. Attempting a similar workload in Java gives a figure of around 11,000 thread creations and teardowns per second – to my mind, a clear demonstration of one of the main advantages of Erlang’s extremely lightweight processes.

Here’s the Java code I used – see the earlier post for the Erlang code, to compare:

// Java 5 – uses a BlockingQueue.
import java.util.concurrent.*;

public class SpawnTest extends Thread {
public static void main(String[] args) {
int M = Integer.parseInt(args.length > 0 ? args[0] : “1″);
int N = Integer.parseInt(args.length > 1 ? args[1] : “1000000″);
int NpM = N / M;
BlockingQueue queue = new LinkedBlockingQueue();
long startTime = System.currentTimeMillis();
for (int i = 0; i < M; i++) { new Body(queue, NpM).start(); }
for (int i = 0; i < M; i++) { try { queue.take(); } catch (InterruptedException ie) {} }
long stopTime = System.currentTimeMillis();
System.out.println((NpM * M) / ((stopTime – startTime) / 1000.0));
}

public static class Body extends Thread {
BlockingQueue queue;
int count;
public Body(BlockingQueue queue, int count) {
this.queue = queue;
this.count = count;
}
public void run() {
if (count == 0) {
try { queue.put(this); } catch (InterruptedException ie) {}
} else {
new Body(queue, count – 1).start();
}
}
}
}

FacebookTwitterGoogle+

23 Comments

  1. badger says:

    How about a benchmark of JMS (or similar)?

  2. tonyg says:

    @badger: Do you mean for testing IPC throughput? That’s a little out-of-scope here, I think; or does JMS have something to say about straight thread-creation time that I’m not seeing?

    Note that the use of BlockingQueue is a convenience for performing the equivalent of Thread.join in the linear chain of created threads I’m testing – BlockingQueue is not a central part of the test.

  3. Isaac Gouy says:

    Concurrency benchmarks are perhaps the least successful part of The Computer Language Shootout – too many different ways to implement concurrency for a sensible comparison.

    Nonetheless we have chameneos and cheap-concurrency.

  4. badger says:

    I was thinking of some sort of Java message passing benchmark. Is there a more lightweight means of doing this than JMS?

  5. matthias says:

    Isaac Gouy wrote:

    Concurrency benchmarks are perhaps the least successful part of The Computer Language Shootout – too many different ways to implement concurrency for a sensible comparison.

    Case in point: the Erlang code for cheap-concurrency is cheating. Unlike all the other implementations I have looked at it waits for each number to ripple through the entire pipeline of processes before injecting the next number. That results in zero parallelism (at any one time only one process can actually make process), zero queuing and zero contention.

  6. Ron says:

    I don’t think you can compare these things. An erlang process does not start an actual thread in the operating system like java does. I’d almost be vaguely interested in seeing a comparison between erlang processes and protothreads and windows fibers.

  7. tonyg says:

    @Ron: The difference between the systems is precisely the interesing point. Java has no analogue to Erlang’s lightweight processes. The best you can do is either threads or hand-rolled explicit continuation passing style. It comes down, IMO, to the differences in philosophy: the Erlang virtual machine is designed around concurrency; the Java VM has concurrency crudely bolted on.

    @Badger: I have done a few quick experiments with the new Java 5 java.util.concurrent.BlockingQueue implementation – I’ll post on those soon. (Briefly: Erlang wins by a factor of about three (for what I called “oneway” the other day) on a single-CPU machine, but for some reason loses badly on a multicore machine)

  8. Julian Morrison says:

    Does Erlang use cooperative, single kernel-process “green” threads? That would explain why it loses on multicore. Java threads can be scheduled per CPU.

  9. tonyg says:

    @Julian: Yes, it does (roughly), but that’s not the reason it’s losing – I’ll explain further when I post about the comparisons I ran in more detail.

  10. Robert Fisher says:

    Java has no analogue to Erlang’s lightweight processes.

    That’s not exactly true. Java threads do not have to be implemented as kernel threads. In fact, a big complaint with Java early on was that many JVMs didn’t use kernel threads & thus couldn’t take full advantage of multiple processors. I got these exactly this sort of results when comparing various JVMs years ago.

    The real drawback with Java here is that it forces JVMs to choose one thread model for everything rather than being able to expose multiple multitasking models to the programmer.

  11. Isaac Gouy says:

    matthias wrote … the Erlang code for cheap-concurrency is cheating
    Argue that in the discussion forum, let’s be considerate and not hijack this blog.

  12. badger says:

    @tony: Cool. I’ll read up on java.util.concurrent.BlockingQueue in the meantime. You’re right about concurrency in Java, java.util.concurrent is truly a horror! ;)

    @julian: The most recent version of Erlang is SMP aware.

  13. Bryce Leo says:

    blink blinkblink
    Sun Workstation, Opteron 150, 1gig ram, Redhat
    Java:27055
    Erlang. 1.03332e+6

    1 million something?

    Goodness…. And you’d figure that a Sun workstation would be where java would somehow be champ.

  14. Denis says:

    Come on, no Java developer writes code like that.

    import java.util.concurrent.*;

    public class Test25 extends Thread {
    public static Executor executor;

    public static void main(String[] args) throws InterruptedException {
        int M = Integer.parseInt(args.length &gt; 0 ? args[0] : "1");
        int N = Integer.parseInt(args.length &gt; 1 ? args[1] : "1000000");
        executor = Executors.newFixedThreadPool(M);
        int NpM = N / M;
        BlockingQueue queue = new ArrayBlockingQueue(1000 * 1000);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i &lt; M; i++) executor.execute(new Body(queue, NpM));
        for (int i = 0; i &lt; N; i++) queue.take();
        long stopTime = System.currentTimeMillis();
        System.out.println((NpM * M) / ((stopTime - startTime) / 1000.0));
    }

    public static class Body implements Runnable {
        BlockingQueue queue;
        int count;
        public Body(BlockingQueue queue, int count) {
            this.queue = queue; this.count = count;
        }
        public void run() {
            try {
                for (int i = 0; i &lt; count; i++) queue.put(this);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    }

    Makes 1.5mln/sec on 3ghz P4 (windows xp)
    It uses a thread pool and a loop instead of recursion.

  15. tonyg says:

    Denis, you’ve missed the point: I’m measuring how many thread creations and teardowns per second the system tops out at, not how many messages per second the system can send with a fixed pool of workers. Note the indirectness of the recursion in the run() method – it spawns a whole new thread for each step of the recursion.

  16. Denis says:

    Tonyg, yeah, I do understand that. But is it required (by some good reason) to create new threads each time?

    I mean that in Java in order to achieve high performance developers do use pool of workers which actually does the same work as if there will be a lot of threads spawned.

    I believe that there is no practical task which could not be solved with pool of workers, if the worker is blocked by network IO we can always use the non-blocking IO.

    So, I mean that actually Java can do better then Erlang on concurrent programming if it’s used properly, keeping in mind it’s limitations and advantages.

  17. tonyg says:

    Denis, see my comment number 7 above. Beware of the Turing tarpit! If you need to support, say, 100,000 genuinely concurrent activities, you have two options: using the threads provided by the language, or modelling threads using a hand-rolled CPS transform. Java’s native threads don’t scale for one reason (heavyweight JVM implementation), as we see above for one axis of measurement, and pseudothreading-by-CPS doesn’t scale for another (human fallibility, poor compositionality). The test I wrote was a simple way of gauging how an Erlangish style of programming might perform in Java. The point I’m interested in is that Erlang’s lightweight threads make programming highly concurrent systems natural, in a way that Java’s threads never will (modulo possible-but-unlikely wholesale revisions of the language).

  18. Denis says:

    Tonyg, I got your point, but most of examples where we need to run 100k of concurrent activities are invented around slow IO. The most frequent case is the web server with massive number of keepalive concurrent users.

    Such tasks are solved in Java by using the non blocking IO and a single thread which does actual processing. With modern framework such progamming style is either completely transparent to program or very simple to use. See AsyncWeb & the Grizzly/Glassfish.

    Also, I think that the thread pool is extremally helpful & provides simplicity identical to thread spawning in 90% of cases.

    Actually Java used to had a number of lightweighted thread implementations like famous green threads or JRockit thinthreads. All of them was invented to cope slow Linux threading before kernel 2.6 & NPTL and dropped immediately after kernel 2.6 was adopted. Simply because there are no real business cases for Java there such kind of lightweight processes are useful.

    Could you please give me the real world sample of task which is not a subject to solve via simple thread pool and is not IO bound?

    Also, why Erlang has slow message passing in SMP configuration? The reason is the lack of good scheduler which can’t place dependant processes in the single OS thread?

  19. Rodrigo B. de Oliveira says:

    @Denis, think simulation. Thousands of active agents interacting with each other.

  20. ChrisH says:

    Denis is correct, Tony none of your arguments hold water.

    Your basically arguing green threads vs native threads not Java vs Erlang, both of which I believe come in various threading flavours.

    The thread limits, memory etc is an OS thing , not Java vary your JVM you’ll get different results e.g. an early JVM will most likely green thread and with bad coding like yours possibly beat the new JVM on a single core .

    Yes a badly written Java app, particularly on a very old JVM (not too old mind as the very old ones tend to be green threaded and that would give Java a chance) on a single core machine can be beaten by a green thread App even Visual Basic .

    … but surprise if you use modern Java or allow threading pooling and/or combine with multicore and your Erlang looks like its in big trouble.

    “Thousands of active agents interacting with each other” so what, no problem, don’t create an OS thread per agent, Erlang isn’t !! it just makes a representation of a thread, Java can do that.

    PS Note in no way am I commenting on the elegance of the languages purely on the benchmarks.

  21. tonyg says:

    ((I accidentally deleted a bunch of comments I didn’t mean to delete today, so I’m having to repost them manually:))

    VB wrote:

    To ChrisH:

    “Thousands of active agents interacting with each other” so what, no problem, don’t create an OS thread per agent, Erlang isn’t !!”

    How would you model the agent then? With a state machine?
    This is going to be a hell.

    By the way, Erlang is not about green threads but about share-nothing, side-effectlessness, concurrency and composability. It’s just better suitable for concurrency than Java, that’s it.

  22. frelankielee says:

    “that’s it” means you can not prove it?

  23. fumanchuman says:

    Bra Dude,

    You are seriously missing the point. Erlang’s “processes” aren’t real processes. The runtime treats them like tasks and has to schedule them on real OS threads.

    You can simulate millions of agents quite naturally in a singe thread. Take a look at n-body simulations etc. State is persisted in a variety of arrays and the effect of dynamics occurring in parallel in simulated by applying the rules of motion to each element. This can easily be parallelized by dividing the state updates amongst available processors and waiting for a barrier to be reached before advancing.

Post a comment

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>