Hacker Timesnew | past | comments | ask | show | jobs | submitlogin

An example of basic concurrency I have great difficulty doing correctly in Java:

  n = 0;
  avg = 0;

  function twothings() {
    thing1(function(ret) { ++n; avg += (ret - avg)/n; });
    thing2(function(ret) { ++n; avg += (ret - avg)/n; });
  }
I want to dispatch two I/O operations to run concurrently and have their completions modify some shared state in a serializable fashion, which can be read at any stage in the process and have a valid result. I shouldn't need to give up on nondeterministic simultaneous execution or faff about with locking mechanisms to get this.


What I think you're missing is that in JS, this is not being run concurrently. Existing JS runtimes are single-threaded—if you actually want to take advantage of multiple CPUs you must run more than one process. It's very easy not to have concurrency bugs when there's no concurrency.

In Java, you have access to real threads and can actually run two pieces of code concurrently. This introduces a lot of potential issues, but also allows you to take advantage of multiple cores.

If all you want is non-blocking IO (what node gives you), there are a handful of great libraries that provide that on the JVM.


If you're having trouble with that, I suggest you take a look at CompletableFuture, or ExecutorCompletionService, or any other number of methods to do this in Java. Just like node has it's own lingo, so does Java, and once you learn it, things become real simple.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: