What advantages does Scala have over Java for conc

2019-03-15 10:47发布

问题:

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?

回答1:

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)



回答2:

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.



回答3:

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.