How To Install Scala In Eclipse
Getting Started Tutorial (Scala with Eclipse): First Chapter
Introduction
Welcome to the commencement tutorial on how to go started with Akka and Scala. We assume that yous already know what Akka and Scala are and will now focus on the steps necessary to offset your first project. We volition exist using Eclipse, and the Scala plugin for Eclipse.
The sample application that we will create is using actors to summate the value of Pi. Calculating Pi is a CPU intensive functioning and we will use Akka Actors to write a concurrent solution that scales out to multi-core processors. This sample will exist extended in future tutorials to use Akka Remote Actors to scale out on multiple machines in a cluster.
We volition exist using an algorithm that is called "embarrassingly parallel" which but means that each job is completely isolated and not coupled with any other job. Since this algorithm is so parallelizable it suits the actor model very well.
Here is the formula for the algorithm nosotros will employ:
In this item algorithm the principal splits the series into chunks which are sent out to each worker actor to be processed. When each worker has processed its chunk it sends a consequence back to the main which aggregates the full result.
Tutorial source lawmaking
If you lot want don't want to type in the code and/or prepare an SBT project and so yous can bank check out the full tutorial from the Akka GitHub repository. Information technology is in the akka-tutorials/akka-tutorial-first module. You can likewise browse it online here, with the bodily source code here.
Prerequisites
This tutorial assumes that you have Coffee 1.6 or later installed on you machine and java on your PATH . You also need to know how to run commands in a shell (ZSH, Bash, DOS etc.) and a contempo version of Eclipse (at least iii.6 - Helios).
If you want to run the example from the command line too, you lot need to brand sure that $JAVA_HOME environment variable is set to the root of the Java distribution. You also need to make sure that the $JAVA_HOME/bin is on your PATH :
$ export JAVA_HOME =.. root of java distribution .. $ export PATH = $PATH : $JAVA_HOME/bin Yous can test your installation by invoking java :
$ java - version java version "1.6.0_24" Coffee ( TM ) SE Runtime Environment ( build 1.half dozen . 0 _24 - b07 - 334 - ten M3326 ) Java HotSpot ( TM ) 64 - Fleck Server VM ( build 19.1 - b02 - 334 , mixed mode ) Downloading and installing Akka
To build and run the tutorial sample from the control line, you have to download Akka. If you prefer to use SBT to build and run the sample then you can skip this department and spring to the side by side one.
Permit's get the akka-actors-1.three.1.zilch distribution of Akka from https://akka.io/downloads/ which includes everything nosotros need for this tutorial. Once you take downloaded the distribution unzip it in the binder you would like to accept Akka installed in. In my case I choose to install it in /Users/jboner/tools/ , simply past unzipping it to this directory.
You need to practice i more matter in order to install Akka properly: fix the AKKA_HOME environment variable to the root of the distribution. In my case I'm opening upward a shell, navigating down to the distribution, and setting the AKKA_HOME variable:
$ cd / Users / jboner / tools / akka - actors - one.iii . one $ export AKKA_HOME = `pwd` $ repeat $AKKA_HOME / Users / jboner / tools / akka - actors - 1.3 . 1 The distribution looks like this:
$ ls - 1 config doc lib src - In the config directory we have the Akka conf files.
- In the doc directory we have the documentation, API, doc JARs, and also the source files for the tutorials.
- In the lib directory we take the Scala and Akka JARs.
- In the src directory we take the source JARs for Akka.
The only JAR we will need for this tutorial (autonomously from the scala-library.jar JAR) is the akka-actor-ane.3.ane.jar JAR in the lib/akka directory. This is a self-contained JAR with null dependencies and contains everything we need to write a organization using Actors.
Akka is very modular and has many JARs for containing different features. The core distribution has vii modules:
- akka-actor-1.3.1.jar – Standard Actors
- akka-typed-thespian-i.3.one.jar – Typed Actors
- akka-remote-1.3.i.jar – Remote Actors
- akka-stm-i.3.1.jar – STM (Software Transactional Memory), transactors and transactional datastructures
- akka-http-1.3.i.jar – Akka Mist for continuation-based asynchronous HTTP and too Jersey integration
- akka-slf4j-1.three.one.jar – SLF4J Event Handler Listener for logging with SLF4J
- akka-testkit-1.3.1.jar – Toolkit for testing Actors
We also have Akka Modules containing addition modules exterior the core of Akka. Yous can download the Akka Modules distribution from https://akka.io/downloads/. It contains Akka cadre equally well. Nosotros will not be needing whatsoever modules there today, but for your information the module JARs are these:
- akka-kernel-1.3.i.jar – Akka microkernel for running a bare-bones mini application server (embeds Jetty etc.)
- akka-amqp-i.3.1.jar – AMQP integration
- akka-camel-1.iii.1.jar – Apache Camel Actors integration (it'southward the best way to take your Akka awarding communicate with the rest of the world)
- akka-camel-typed-ane.3.one.jar – Apache Camel Typed Actors integration
- akka-scalaz-i.3.ane.jar – Back up for the Scalaz library
- akka-bound-1.3.1.jar – Leap framework integration
- akka-osgi-dependencies-bundle-1.3.1.jar – OSGi support
Downloading and installing the Scala IDE for Eclipse
If you want to employ Eclipse for coding your Akka tutorial, you lot need to install the Scala plugin for Eclipse. This plugin comes with its own version of Scala, so if you don't programme to run the example from the control line, yous don't demand to download the Scala distribution (and you lot can skip the adjacent section).
Yous can install this plugin using the regular update mechanism. First cull a version of the IDE from http://download.scala-ide.org. Nosotros recommend you choose ii.0.x, which comes with Scala ii.9. Copy the corresponding URL and and so choose Help/Install New Software and paste the URL yous merely copied. You should see something similar to the following image.
Brand sure you select both the JDT Weaving for Scala and the Scala IDE for Eclipse plugins. The other plugin is optional, and contains the source code of the plugin itself.
One time the installation is finished, you demand to restart Eclipse. The first time the plugin starts it will open a diagnostics window and offer to fix several settings, such equally the delay for content assist (code-completion) or the shown completion proposal types.
Accept the recommended settings, and follow the instructions if you need to increase the heap size of Eclipse.
Cheque that the installation succeeded by creating a new Scala projection ( File/New>Scala Project ), and typing some lawmaking. You should take content-assist, hyperlinking to definitions, instant error reporting, and so on.
You lot are gear up to code now!
Downloading and installing Scala
To build and run the tutorial sample from the command line, you accept to install the Scala distribution. If you prefer to apply Eclipse to build and run the sample and then you lot can skip this section and jump to the next one.
Scala can be downloaded from http://www.scala-lang.org/downloads. Browse there and download the Scala 2.9.i release. If you selection the tgz or zip distribution then simply unzip information technology where you desire it installed. If you selection the IzPack Installer so double click on it and follow the instructions.
Y'all as well need to brand sure that the scala-two.9.1/bin (if that is the directory where you lot installed Scala) is on your PATH :
$ export PATH=$PATH:scala-ii.9.1/bin You tin examination your installation past invoking scala:
$ scala - version Scala code runner version ii.ix . ane.f inal -- Copyright 2002 - 2011 , LAMP / EPFL Looks like we are all expert. Finally let'south create a source file Pi.scala for the tutorial and put information technology in the root of the Akka distribution in the tutorial directory (you have to create it offset).
Some tools require you to set the SCALA_HOME environment variable to the root of the Scala distribution, nonetheless Akka does not require that.
Creating an Akka project in Eclipse
If you take not already done so, now is the time to create an Eclipse project for our tutorial. Use the New Scala Project wizard and take the default settings. One time the project is open, we need to add the akka libraries to the build path. Correct click on the project and choose Backdrop , then click on Java Build Path . Get to Libraries and click on Add together External Jars.. , and so navigate to the location where you lot installed akka and choose akka-role player.jar . You should encounter something similar to this:
Using SBT in Eclipse
If you are an SBT user, you can follow the Downloading and installing SBT educational activity and additionally install the sbteclipse plugin. This adds support for generating Eclipse projection files from your SBT project. You lot demand to install the plugin as described in the README of sbteclipse
Then run the eclipse target to generate the Eclipse projection:
The options create-src and with-sources are useful:
$ sbt > eclipse create - src with - sources - create-src to create the common source directories, e.g. src/main/scala, src/chief/test
- with-sources to create source attachments for the library dependencies
Side by side you need to import this project in Eclipse, by choosing Eclipse/Import.. Existing Projects into Workspace . Navigate to the directory where you defined your SBT project and choose import:
Now we have the basis for an Akka Eclipse application, then we can..
Start writing the lawmaking
The blueprint we are aiming for is to have one Master actor initiating the computation, creating a set of Worker actors. So it splits up the piece of work into discrete chunks, and sends these chunks to the different workers in a round-robin way. The principal waits until all the workers have completed their work and sent back results for aggregation. When ciphering is completed the master prints out the issue, shuts down all workers then itself.
With this in heed, let's now create the messages that we want to accept flowing in the organization.
Creating the messages
We get-go by creating a package for our application, let's phone call it akka.tutorial.outset.scala . We start by creating case classes for each type of message in our awarding, so we can place them in a hierarchy, call it PiMessage . Right click on the package and choose New Scala Class , and enter PiMessage for the proper noun of the class.
We need three different letters:
- Calculate – sent to the Master role player to offset the calculation
- Work – sent from the Master role player to the Worker actors containing the piece of work assignment
- Result – sent from the Worker actors to the Master role player containing the upshot from the worker's calculation
Messages sent to actors should always be immutable to avoid sharing mutable state. In Scala nosotros accept 'case classes' which brand first-class messages. And so let's start by creating iii messages equally case classes. We also create a common base trait for our messages (that we define as being sealed in order to prevent creating messages outside our control):
package akka.tutorial.first.scala sealed trait PiMessage case object Calculate extends PiMessage case course Work ( offset : Int , nrOfElements : Int ) extends PiMessage case class Result ( value : Double ) extends PiMessage Creating the worker
At present we can create the worker player. Create a new class called Worker as before. Nosotros need to mix in the Actor trait and defining the receive method. The receive method defines our message handler. Nosotros expect it to be able to handle the Work bulletin so we need to add together a handler for this message:
class Worker extends Actor { def receive = { case Work ( get-go , nrOfElements ) => self reply Outcome ( calculatePiFor ( start , nrOfElements )) // perform the work } } The Actor trait is defined in akka.actor and y'all tin either import it explicitly, or let Eclipse exercise information technology for you when it cannot resolve the Actor trait. The quick prepare option ( Ctrl-F1 ) will offer 2 options:
Choose the Akka Actor and movement on.
Equally you can encounter we have now created an Actor with a receive method every bit a handler for the Work bulletin. In this handler nosotros invoke the calculatePiFor(..) method, wrap the consequence in a Result message and ship it back to the original sender using self.respond . In Akka the sender reference is implicitly passed along with the message so that the receiver tin can always reply or shop away the sender reference for future employ.
The just thing missing in our Worker actor is the implementation on the calculatePiFor(..) method. While there are many ways we can implement this algorithm in Scala, in this introductory tutorial we take called an imperative manner using a for comprehension and an accumulator:
def calculatePiFor ( beginning : Int , nrOfElements : Int ) : Double = { var acc = 0.0 for ( i <- start until ( start + nrOfElements )) acc += 4.0 * ( ane - ( i % 2 ) * 2 ) / ( ii * i + 1 ) acc } Creating the principal
Now create a new class for the chief actor. The master histrion is a little chip more involved. In its constructor we need to create the workers (the Worker actors) and start them. We will as well wrap them in a load-balancing router to make information technology easier to spread out the piece of work evenly between the workers. First we need to add some imports:
import akka.role player. { Actor , PoisonPill } import akka.routing. { Routing , CyclicIterator } import Routing._ import akka.acceleration.Dispatchers import java.util.concurrent.CountDownLatch and then we can create the workers:
// create the workers val workers = Vector . fill ( nrOfWorkers )( actorOf [ Worker ]. start ()) // wrap them with a load-balancing router val router = Routing . loadBalancerActor ( CyclicIterator ( workers )). offset () As yous can come across we are using the actorOf factory method to create actors, this method returns as an ActorRef which is a reference to our newly created player. This method is available in the Actor object but is usually imported:
import akka.thespian.Role player.actorOf There are two versions of actorOf ; one of them taking a actor type and the other i an instance of an player. The former one ( actorOf[MyActor] ) is used when the role player class has a no-argument constructor while the second one ( actorOf(new MyActor(..)) ) is used when the actor class has a constructor that takes arguments. This is the only way to create an instance of an Actor and the actorOf method ensures this. The latter version is using phone call-past-proper name and lazily creates the actor within the scope of the actorOf method. The actorOf method instantiates the actor and returns, not an instance to the histrion, only an case to an ActorRef . This reference is the handle through which you communicate with the actor. It is immutable, serializable and location-aware meaning that it "remembers" its original actor fifty-fifty if it is sent to other nodes across the network and tin be seen equally the equivalent to the Erlang actor's PID.
The actor's life-bike is:
- Created – Player.actorOf[MyActor] – tin can not receive messages
- Started – actorRef.offset() – tin receive messages
- Stopped – actorRef.stop() – can not receive letters
Once the actor has been stopped it is dead and can not be started again.
Now we have a router that is representing all our workers in a single abstraction. If you paid attending to the code in a higher place, y'all saw that we were using the nrOfWorkers variable. This variable and others we have to pass to the Master actor in its constructor. So now let'south create the master actor. We have to pass in three integer variables:
- nrOfWorkers – defining how many workers we should start upwardly
- nrOfMessages – defining how many number chunks to send out to the workers
- nrOfElements – defining how big the number chunks sent to each worker should be
Here is the master player:
course Master ( nrOfWorkers : Int , nrOfMessages : Int , nrOfElements : Int , latch : CountDownLatch ) extends Actor { var pi : Double = _ var nrOfResults : Int = _ var first : Long = _ // create the workers val workers = Vector . fill ( nrOfWorkers )( actorOf [ Worker ]. beginning ()) // wrap them with a load-balancing router val router = Routing . loadBalancerActor ( CyclicIterator ( workers )). start () def receive = { ... } override def preStart () { start = Organization . currentTimeMillis } override def postStop () { // tell the world that the calculation is complete println ( "\n\tPi approximate: \t\t%due south\n\tCalculation time: \t%south millis" . format ( pi , ( System . currentTimeMillis - start ))) latch . countDown () } } A couple of things are worth explaining further.
Outset, we are passing in a java.util.concurrent.CountDownLatch to the Principal thespian. This latch is only used for plumbing (in this specific tutorial), to have a elementary way of letting the exterior globe knowing when the master can evangelize the consequence and shut downwardly. In more idiomatic Akka code, as we will run across in part ii of this tutorial series, nosotros would non utilize a latch but other abstractions and functions similar Channel , Future and ? to attain the same affair in a non-blocking way. But for simplicity let's stick to a CountDownLatch for at present.
Second, we are adding a couple of life-wheel callback methods; preStart and postStop . In the preStart callback we are recording the time when the actor is started and in the postStop callback we are printing out the result (the approximation of Pi) and the fourth dimension it took to calculate it. In this telephone call we besides invoke latch.countdown to tell the outside globe that nosotros are done.
But we are not washed yet. Nosotros are missing the message handler for the Chief role player. This bulletin handler needs to exist able to react to two different messages:
- Calculate – which should get-go the adding
- Effect – which should amass the different results
The Calculate handler is sending out work to all the Worker actors and later doing that it also sends a Broadcast(PoisonPill) message to the router, which volition ship out the PoisonPill message to all the actors it is representing (in our case all the Worker actors). PoisonPill is a special kind of message that tells the receiver to shut itself down using the normal shutdown method; self.stop . We too send a PoisonPill to the router itself (since it'southward likewise an actor that we want to shut down).
The Issue handler is simpler, here we go the value from the Result message and aggregate it to our pi member variable. Nosotros as well go on track of how many results nosotros have received back, and if that matches the number of tasks sent out, the Principal role player considers itself done and shuts down.
Let'due south capture this in code:
// bulletin handler def receive = { case Calculate => // schedule piece of work for ( i <- 0 until nrOfMessages ) router ! Work ( i * nrOfElements , nrOfElements ) // send a PoisonPill to all workers telling them to shut downward themselves router ! Broadcast ( PoisonPill ) // send a PoisonPill to the router, telling him to shut himself downwards router ! PoisonPill case Result ( value ) => // handle event from the worker pi += value nrOfResults += 1 if ( nrOfResults == nrOfMessages ) self . stop () } Bootstrap the calculation
Now the merely affair that is left to implement is the runner that should bootstrap and run the adding for usa. We practise that past creating an object that we telephone call Pi , here we can extend the App trait in Scala, which means that we will be able to run this as an application directly from the command line or using the Eclipse Runner.
The Pi object is a perfect container module for our actors and messages, and then let's put them all there. We also create a method calculate in which we start up the Master actor and wait for it to finish:
object Pi extends App { calculate ( nrOfWorkers = 4 , nrOfElements = 10000 , nrOfMessages = 10000 ) ... // actors and messages def calculate ( nrOfWorkers : Int , nrOfElements : Int , nrOfMessages : Int ) { // this latch is only plumbing to know when the calculation is completed val latch = new CountDownLatch ( one ) // create the master val primary = actorOf ( new Chief ( nrOfWorkers , nrOfMessages , nrOfElements , latch )). outset () // start the calculation main ! Calculate // wait for primary to shut down latch . await () } } That's information technology. Now nosotros are washed.
Run it from Eclipse
Eclipse builds your project on every salve when Project/Build Automatically is set. If not, bring you lot project up to engagement past clicking Projection/Build Project . If there are no compilation errors, yous tin right-click in the editor where Pi is defined, and cull Run as.. /Scala application . If everything works fine, y'all should see:
AKKA_HOME is defined as [/Users/jboner/tools/akka-actors-1.3.ane] loading config from [/Users/jboner/tools/akka-actors-1.three.1/config/akka.conf]. Pi approximate: 3.1435501812459323 Calculation fourth dimension: 858 millis If you accept not defined an the AKKA_HOME environment variable so Akka can't find the akka.conf configuration file and will print out a Tin can't load akka.conf alert. This is ok since it will then just apply the defaults.
You can besides define a new Run configuration, by going to Run/Run Configurations . Create a new Scala application and choose the tutorial project and the main grade to be akkatutorial.Pi . You can pass additional control line arguments to the JVM on the Arguments page, for example to define where akka.conf is:
Once you finished your run configuration, click Run . You should see the aforementioned output in the Panel window. You tin can use the same configuration for debugging the application, by choosing Run/Debug History or but Debug As .
Conclusion
We have learned how to create our first Akka project using Akka'due south actors to speed up a computation-intensive problem by scaling out on multi-core processors (also known as scaling up). Nosotros accept also learned to compile and run an Akka project using Eclipse.
If you have a multi-core machine then I encourage you to endeavour out unlike number of workers (number of working actors) past tweaking the nrOfWorkers variable to for example; ii, four, 6, 8 etc. to encounter functioning improvement past scaling up.
Now we are prepare to take on more advanced problems. In the side by side tutorial we will build on this one, refactor information technology into more idiomatic Akka and Scala code, and introduce a few new concepts and abstractions. Whenever you feel prepare, join me in the Getting Started Tutorial: Second Affiliate.
Happy hakking.
Source: https://doc.akka.io/docs/akka/1.3.1/intro/getting-started-first-scala-eclipse.html
Posted by: carpentercomay1968.blogspot.com

0 Response to "How To Install Scala In Eclipse"
Post a Comment