14

How can scala make writing multi-threaded programs easier than in java? What can scala do (that java can't) to facilitate taking advantage of multiple processors?

Gordon Gustafson
  • 40,133
  • 25
  • 115
  • 157
  • 4
    Java can do anything Scala can do, and vice versa. They both run in the JVM, and they're both Turing-complete, so by definition either one can do the same things as the other. The difference is what's easier or more natural in one language than the other. – cHao Aug 20 '10 at 23:10
  • @cHao @Zan edited question to more closely address the issue. :) – Gordon Gustafson Aug 20 '10 at 23:15

3 Answers3

15

The rules for concurrency are

1 avoid it if you can

2 share nothing if you can

3 share immutable objects if you can

4 be very careful (and lucky)

For rule 2 Scala helps by providing a nicely integrated message passing library out of the box in the form of the actors.

For rule 3 Scala helps to make everything immutable by default.

For rule 4 Scala's flexible syntax allows the creation of internal DSL's making it easier and less wordy to express what you need consicely. i.e. less place for surprises (if done well)

Peter Tillemans
  • 34,983
  • 11
  • 83
  • 114
  • 1
    I think #1 is increasingly becoming difficult to do. I'd say that using a framework, e.g. map-reduce or some fork-join library, can help you write concurrent programs without having it feel concurrent. – jsuereth Aug 21 '10 at 13:47
  • I agree. It definitely pays to carefully examine your needs and select concurrency patterns which fit these. And then use a debugged library/framework which implement these. – Peter Tillemans Aug 22 '10 at 19:30
  • 1
    #1 Needs to come of the list; rather we should be actively looking for ways to exploit the multiple CPU cores available on modern computers. – Lawrence Dol Jan 15 '11 at 05:25
12

If one takes Akka as a foundation for concurrent (and distributed) computing, one might argue the only difference is the usual stuff that distinguishes Scala from Java, since Akka has both Java and Scala bindings for all its facilities.

Randall Schulz
  • 26,420
  • 4
  • 61
  • 81
6

There is nothing Scala does that Java does not. That would be silly. Scala runs on the same JVM that Java does.

What Scala does do is make it easier to write, easier to reason about and easier to debug a multi-thread program.

The good bits of Scala for concurrency are its focus on immutable objects, its message-passing and its Actors.

This gives you thread-safe read-only data, easy ways to pass that data to other threads, and easy use of a thread pool.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131
  • 2
    I'd add closures to it. It really makes a lot of things easier. – Daniel C. Sobral Aug 21 '10 at 05:37
  • 1
    I'd also add the delimited continuations really change the playing field for writing concurrent programs. Hopefully the amazing library support pops up in a few months. – jsuereth Aug 21 '10 at 13:47