Tuesday Feb 21, 2012

Java EE 6 workshop delivered at Umeå JUG


What's common between Austin (Texas), Reykjavik (Iceland), Stockholm (Sweden), and Umeå (Sweden) ?
  • They all had a Java EE 6 workshop in the past 2.5 weeks
  • All of them had fairly higher attendance than normal/expected
  • Every where the attendees stayed much longer than originally planned
  • The simplicity and power of awesome threesome of Java EE 6, NetBeans, and GlassFish was very well appreciated by the attendees

The recently concluded workshop at Umeå JUG proved yet again how Java EE 6 can easily attract audience. And now that WebLogic and GlassFish are Java EE 6 compatible, there is a wide variety of containers available to deploy your applications.

This JUG, part of Javaforum Sweden, is the second most northern JUG (Reykjavik is the northern most by about 150 km) in a small university town of about 115,000. The constant sub-zero temperature and tons of snow during my stay made the cross-country an interesting first time experience. Running outside in the cold was harder than I originally thought as the cheeks were getting cold and making it difficult to talk. Thank you Jonas for teaching me the basic skills and sharing your spiked running shoes. Quite an enjoyable experience over all!

The interactive attendees learned all about:

  • Improvements in Java Persistence API 2
  • "web.xml"-free and annotation-driven Servlets
  • Simplified packaging of EJBs in a WAR file, no-interface and single file definition of EJB
  • Session preservation across redeploys
  • Facelets (XHTML/CSS) as templating language for JavaServer Faes to achieve true MVC
  • Integration of Bean Validation with JPA and JSF
  • Typesafe dependency injection and Producer/Observer of events using CDI
  • RESTful resources using JAX-RS

The hands-on lab document is available here and the complete application here.

Here is a picture with Jonas and Mattias - the JUG leaders. Their mission is to learn and spread knowledge about Java in Umeå by bringing in speakers from all around the world. A local tech publication (InfoTech Umeå) also talked about the workshop. Here is a picture from the article:


Jonas, Arun,
Mattias at Umeå JUG
(Image Credits: InfoTech Umeå)

And some more pictures from the visit ...





The complete photo album is available at (pictures are from trip to JUGICE and Jfokus)  ...



Next stop 33rd Degree and Codemotion ...

Friday Aug 12, 2011

Dallas Tech Fest 2011 Trip Report

You're in Texas when 85F at 8:30am is not considered warm or there is a 28-day spell of 100F :-)

Dallas Tech Fest, used to be called as Dallas Code Camp, has its fourth annual conference running in, of course, Dallas. The agenda was packed with 100+ sessions by 70+ speakers over 2 days. This is the first time the event has expanded from the usual one day to two day format. With up to 10 sessions running in parallel, about 300 attendees (my guess) had a lot to choose from.

This was my second year in a row and I gave a 3 hr workshop on Java EE 6 and also talked about how GlassFish 3.1 is the best platform for deploying your Java EE 6 applications.

The slides are available:


There were about 30 attendees in/out of the workshop with a high degree of interaction. The slides provide the code templates in the workshop and the actual detailed steps will also be available as a screencast soon. The complete code built during the workshop can be downloaded here.

The GlassFish 3.1 slides are also available:
 

Did you know that GlassFish 3.1.1 runs on JDK 7 ? TOTD #169 shows how to use multi-catch, TOTD #168 shows how to use Switch statement in Strings, and TOTD #167 explains how to use Automatic Resource Management to write optimized and cleaner code.

The overall logistics of the event pretty flawless and University of Texas is a beautiful location other than the 100C temperature ;-) I wanted to attend the Community Leadership Townhall but decided to leave early to reach home on time for a Hindu festival over the weekend.

You can follow the twitter stream at #dtf11. One thing that was quite obvious was the intrusion caused by the event photographers. I certainly experienced that as a speaker and I saw several tweets by attendees feeling annoyed as well. The shutter clicks were fairly loud, the flash was right in the eyes (without a bounce), they were going in way too close to the speakers (probably because of lower ISO), and sometimes even obstructing attendees' view too ;-) IMHO, they should take lessons from James Duncan Davidson who do a marvellous job of capturing photographs of different O'Reilly conferences.

Here are some pictures captured from the event:

Many thanks to Tim Rayburn and Erik Weibust - the fearless local community leaders - for providing me with an opportunity to share the technology and my passion with the audience.

A decent 7mile run at the nearby Anderson Donner Park with a single track running trail for a few miles was an overall good beginning to the day anyway:

And finally the complete photo album at:

Friday May 27, 2011

Athens, Greece is now Java EE 6 and GlassFish-enabled!

About 15 developers in Athens are now ready to start cranking your Java EE 6 applications after getting an extensive 2-day training by Oracle Education!

Are you still building your enterprise applications using proprietary frame works ? If yes, ouch, I feel sorry for you :-) Free yourself from the shackles and build your applications using standards-based approach of Java EE 6. The consistent feedback that we've heard from our users is ...

  • Developers can concentrate on business logic, Java EE 6 is providing a standard for the infrastructure.
  • Definite excuse to avoid Spring forever
  • Standards compliance, vendor independence, milliseconds and kilobyte deployment
  • Not your fat grandfather's enterprise Java anymore, enterprise Java renaissance
  • Jigsaw puzzle, Modular, standard, less xml, easy, easy, have I said easy?

Read complete details and love for Java EE 6 from the different community members of such feedback here.

This was third workshop of the year (after Budapest and Slovakia) and the attendees were very interactive. I was pretty impressed by the fact that any email checking was restricted during the breaks only and I had attendees' full attention during the lectures. Each attendee had their own laptop confiured with NetBeans and GlassFish and could successfully complete the different hands-on labs as well. Of course, as always, there were kinks with Windows ;-)

I also spoke at the Hellenic Java User Group (Greek JUG) and those 2 hours were extremely interactive. Read more detailed report on that here. Here is a picture captured from the blog:

I really enjoyed the comfortable setting and "religious" discussions around different stacks :-) Many thanks to Paris Apostolopoulos, the JUG leader, for providing me a chance to engage with the community and spread some more Java EE 6 goodness!

Its amazing how vast the technology is and more importantly the customer's innovative ways of using it to solve their business problems. I've learned new concepts, refined existing ones, and added bullet points (in a continuously evolving slide deck) for a better explanation.

This was my first time in Athens and I felt terribly excited to be in the city where marathon was born. But my hotel was right in the middle and so running with full traffic would've been a challenge. However I did couple of half-marathons on the bike, one 10k and one quarter marathon run in the gym - so all activities were centered around a marathon distance :-)

Athens Metro is very well organized and is a good way to go around the city. It definitely connects the key tourist spots. I experienced a gathering of about 5000 Greeks on the way to the JUG venue. They were protesting against the current economic situation in the country, fortunately it was a silent one ;-) 

And finally the complete album:



Next stop: Cloud Computing Expo New York City, New York City Java Meetup (details coming up), South East Linux Fest (SELF) 2011 (PDF), and South Carolina JUG.

Technorati: conf greece javaee6 glassfish netbeans workshop greek jug

Monday May 16, 2011

Java EE 6/GlassFish at Greek JUG (FREE) and 2-day Java EE 6 workshop in Athens (Paid)

After Budapest and Slovakia, the 2-day deep dive Java EE 6 workshop by Oracle University is now going to Athens - one of the world's oldest cities and finish line of the world's first marathon. As part of this workshop, you'll learn the complete nuts and bolts of Java EE 6 and several component technologies.

When ? May 26/27

Where ? Athens, Greece

Register here!

And as part of the visit, I'll also be speaking on Java EE 6 / GlassFish at the Greek JUG (aka Java Hellenic User Group) on May 25th. More details are available in the links below:


And since Greece is the city to boast about finish line of the world's first marathon, I'm very much up for running on the 25/26/27 mornings. Anybody interested ?

Technorati: conf workshop greece athens javae6 glassfish

Tuesday Apr 19, 2011

2 day Java EE 6 Workshop at Bratislava, Slovakia Delivered

I just completed my second (first in Budapest) 2-day Java EE 6 workshop, this time in Bratislava, Slovakia. Thank you Oracle University!

The workshop covered the majority of Java EE 6 technologies such as EJB 3.1, JPA 2, JSF 2, Servlets 3, CDI 1.0, Bean Validation 1.1, and had several hands-on components using NetBeans and Eclipse. I also gave an update on GlassFish 3.1 and all the features typically offered for deploying your Java EE 6 applications. And also added a session on OSGi-enabled Java EE Applications. The timing was much better coordinated from the last workshop, had more time for hands-on sessions, and all attendees could complete them.

The number of attendees was definitely small but that allowed me to engage into 1-1 conversation easily, and all of them were quite engaging. Here is some feedback from the attendees on how Java EE 6 and GlassFish will simplifying development and deployment:

  • Lot of annotations makes the life extremely simple but still have the choice to use XML to override them.
  • Provides a light-weight installation which has a small footprint, intuitive IDE experience for NetBeans. This is the same feedback also mentioned by customers.
  • Don't use Tomcat, use GlassFish.
  • Good starting point for EJB as well as CDI. The misconception is that using Seam is the most easy to start with EJB, but don't think that's true with all the simplifications in EJB 3.1.
  • New extensions mechanism in the platform makes possible to develop and deployon standard platforms, at the same time keep track with innovation
  • Concepts of JSF2 with XHTML layout and easy way to define composite components is very compelling
  • OSGi platform on top of Java EE is a good one, compared to heavy Java modular system in the past

You can always a read more detailed feedback on Java EE 6 in this community feedback series.

If you are interested then similar workshops are also planned in Utrecht, Netherlands on May 23/24 (register here) and Athens, Greece on May 26/27 (register here)!

On a personal front, the hot water + lemon + honey helped me keep my voice and throat soothing. A very nice fitness center (Golem Club) in a close by shopping complex, with elaborate set of workout machines, also helped me maintain my workout regime. :-)

Here are a few shots from the neighborhood:

And also managed to get a long run in the neighborhood as well:


On an unrelated note, one of the attendees asked me where to buy Oracle merchandise:

oraclestore.corpmerchandise.com is your answer!

Check out several other offerings from Oracle University at education.oracle.com.

Technorati: conf slovakia workshop javaee6 glassfish

Monday Jan 24, 2011

2-day Java EE 6 workshop in Budapest - Delivered, More coming!

I delivered a 2-day Java EE 6 workshop in Budapest last week. This was my longest speaking engagement at one shot and I really enjoyed it! There were about 30 attendees and hoefully they enjoyed it too :-)

Other than talking about the key Java EE 6 technologies (CDI, Bean Validation, Servlets 3, JSF2, JPA2, EJB 3.1), the 2-day workshop gave ample time to show NetBeans and Eclipse live coding sessions and interact with the attendees. Here is some feedback from the attendees:

  • We expect more productivity and cleaner code with Java EE 6.
  • Simplified EJB development without XML DD.
  • Good mixture & collection of effective tools of coding styles today, seems really effective.
  • Like CDI, better than Spring because of no XML DD. Hate XML.
  • CDI is one of the most powerful features of Java EE 6, make it easier with web tier, also makes it possible to introduce new annotations.
  • Opens the barrier, not so rigorous, more flexible, For example EJBs in web container.
  • Auto-deploy is great
  • JSF is usable.
  • Programmers Non-standrd way to solve problems, Java EE 6 is solving that problem.
  • Improvements of EJB testability.

This workshop is also getting scheduled at the following locations (provided enough attendees register) ...

Here are some pictures from Budapest ...


Also managed to get another run by River Danube:

And now the complete photo album:

Technorati: conf javaee6 glassfish netbeans eclipse

Wednesday Jan 05, 2011

2 day Java EE 6 Workshop in Budapest, Hungary - Jan 20/21, 2011

Oracle University is organizing a 2-day Java EE 6 workshop in Budapest, Hungary and I'll be speaking!

This workshop will cover the nuts and bolts of the Java EE 6 platform and telling you everything about the new/updated specifications in the platform from Contexts & Dependency Injection (JSR 299), Bean Validation (JSR 303), RESTful Web services (JSR 311), Enterprise Java Beans 3.1 (JSR 318), Servlets 3.0 (JSR 315), Java Server Faces 2.0 (JSR 314), Java Persistence API 2.0 (JSR 317), NetBeans/Eclipse tooling and the whole shebang!

Are you interested ? Register today!

Make sure to bring your laptops to get your hands dirty.

Budapest is cited as one of the most beautiful cities in Europe but unfortunately I'll barely get any time to go around the city. However I'll still be interested in a run together ? I know it's going to be cold but would still like to run :-)

Technorati: conf javaee6 glassfish workshop hungary budapest

Wednesday Sep 01, 2010

2-day Java EE 6 & GlassFish workshops in Germany, Czech Republic, Hungary - Register now!

  • Are you interested in learning the nuts and bolts of the Java EE 6 platform ?
  • Do you want to learn on how Servlet 3.0, Java Server Faces 2.0, Context & Dependency Injection 1.0, Enterprise JavaBeans 3.1, Bean Validation 1.0, Java Persistence API 2, RESTful Web services and other new technologies in Java EE 6 provide a complete stack for building your Web & Enterprise applications ?
  • GlassFish 3.1 adds clustering, high availability, application versioning and other interesting featuresm, above light-weight, OSGi-based modularity, and embeddability, making it the richest open source application server.
  • Did you know that NetBeans, Eclipse, and IntelliJ provide comprehensive tooling around Java EE 6 and would like to learn it ?

If you are interested in learning any of these details then I'll be delivering 2-day workshops in 3 countries across Europe. The complete details about the venue and cost are available in the links below:

This is going to be a complete deep dive for 2 days and extensive hands-on experience.

Be ready to drink from the fire hose and learn how you can leverage Java EE 6 in your next project to boost the productivity and simplify the development and deployment of your applications.

Register now!

Technorati: conf javaee6 glassfish workshop germany czech hungary

Wednesday Jun 16, 2010

Uber Conf 2010 - Notes from Scala for Java Programmers Workshop

I spent the first half of Day 3 of Uber Conf 2010 (Day 2 and 1) in Scala for Java Programmers workshop by Venkat, took extensive notes, and noted/tried pretty much all the code samples.

<warning>
This is a code intensive and slightly long entry.
</warning>

A more complete entry covering other events of Day 3 will come later today.

Lets go down the rabbit hole!

  • Why Scala ? - Scala is highly concise, expressive, nice support for XML processing, pattern matching, inherent support for authoring concurrent code - lot of good things to write efficient code.
  • Scala means SCAlable LAnguage - comes from the fact that you can write either a small script or a complete application using Scala.
  • An application developed on single core and deployed on multi-core can easily misbehave, primarily because of the concurrency model in Java. Scala makes it much easier to write concurrent applications (more on this below).
  • Writing correct synchronized code in Java requires divine power. Multi-threaded programming in Java is like working with mother-in-law, basically waiting for you to fail.
  • Scala complies with Java semantics without you worrying about it. "-savedcompile" saves the generated class files as JAR in the local directory.

Here is the first sample code that calculates the factorial of a number:

def fact(number: Int) = {
 var total = 1
 for (i <- 1 to number) {
     total = total \* i
 }
 total
}

println(fact(5))

Key points about this code (differences from Java):

  • Each class is "public" by default
  • No "main" method
  • "return" keyword is not required
  • The index "i" is assigned a type using inference, integer in this case
  • "var" defines a variable

This was done as a user exercise and so I wrote my first Scala code today ... yeee-haw!

  • Recursion is very expressive but expensive because of multiple stacks. Scala makes it run iterative and so less expensive
  • Scala supports tail recursion to a fairly decent extent, only one level of stack and so less expensive.

Here is a re-write of the above function using simple iterative recursion:

def total(number:Int) : Int = {
    if (number == 1)
       return 1
    number \* total (number - 1)
}

println(total(5))

And now this method converted to use tail recursion

def total(number: Int) : Int = {
   def totalWithAccumulator(accumulator: Int, number: Int) : Int = {
       if (number == 1) 
           accumulator
       else
           totalWithAccumulator(accumulator \* number, number - 1)
   }
   totalWithAccumulator(1, number)
}
println(total(5))

Here is a function that calculates the total of elements in a list:

def total(list: List[int]) = {
    var total = 0
    for (e <- list)
       total = total + e
    total
}

val list = List(1,2,4,5,6,3)
println(total(list))

This is using iterative approach - keep modifying the variable over & again and tells the next step. In functional, variables are constant and never changed. And here is a new method using the functional capabilities:


// imperative
def total(list: List[int]) = {
    var total = 0
    for (e <- list)
        total = total + e
    total
}

// functional
def total2(list: List[int]) = {
    list.foldLeft(0) {
       (carryOver, e) => carryOver + e
    }
}

val list = List(1,2,4,5,6,3)
println(total(list))
println(total2(list))

In Scala

a.+(b);

is equivalent to
a + b

".", parentheses, and ";" are optional.

When the method name ends with the colon, Scala will transpose them. The following code snippet shows this and some other features of the language:

val list = List(1,2,4,5,6,3)

// Imperative
var total1 = 0
for (e <- list)
    total1 = total1 + e
println("Total is " + total1)

// Functional
val total2 = list.foldLeft(0) { (carryOver, e) => carryOver + e }
println("Total is " + total2)

// Transposition using colon
// /: is a different name for foldLeft
var total3 = (0 /: list) { (carryOver, e) => carryOver + e }
println("Total is " + total3)

// No name required if the parameters are used only once
var total4 = (0 /: list) { _ + _ }
println("Total is " + total4)

// Pipe the method
def add(op1: Int, op2: Int) = { op1 + op2 }
val total5 = (0 /: list) { add }
println("Total is " + total5)
  • No primitive types in Scala, everything is an object

Code samples of closures in Scala ...

def totalSelectedNumbers(list:List[Int], selector: Int => boolean) = {
    var total = 0
    for (e <- list)
        if (selector(e)) total = total + e
    total
}


val list = List(1,2,4,5,6,3)
println(totalSelectedNumbers(list, { e => true }))
println(totalSelectedNumbers(list, { e => e % 2 == 0 }))
println(totalSelectedNumbers(list, { e => e > 4 }))
println(totalSelectedNumbers(list, { _ > 4 }))

Notice how "println" becomes more concise over subsequent lines. And a further cleaner, and concise, version can be written by allowing multiple lists to be passed to the function as shown below:

// Multiple lists to the function
def totalSelectedNumbers(list:List[Int]) (selector: Int => boolean) = {
    var total = 0
    for (e <- list)
       if (selector(e)) total = total + e
    total
}

val list = List(1,2,4,5,6,3)
println(totalSelectedNumbers(list) { _ > 4 })

Here is another exercise to write a function that doubles the number in the list:

val list = List(1,2,4,5,6,3)
println(list.map { _ \* 2 })

And another exercise to find the maximum number of a list

val list = List(1,2,4,5,6,3,2,7)
val max = (list(0) /: list) { (max, e) =>
             if (e > max) e else max
          }
println (max)


And then a simplified method definition ...

println((list(0) /: list) { Math.max })

  • In Scala: "val" creates a pointer that cannot change, "var" creates a pointer that can change but the objects are immutable.
  • In Scala, everything is public unless you say otherwise.
  • Code within the class runs within the primary constructor. In Scala, there is only one constructor, every other is called as auxiliary constructor and they always go through the primary constructor. Only primary constructor can call super (only path to the base class)

Here is a simple class definition:

class Car(val year: int, var miles: Int) {

    // invokes with primary constructor
    println("hello there")

    // year has a getter, miles has a getter/setter
    def drive(dist: Int) = {
       miles += dist
    }

    // private method only to this instance
    private[this] def tuneup {}
}

val car = new Car(2010, 0)
println(car.year)
println(car.miles)
car drive 10
println(car.miles)
  • Scala is a purely OO language, new methods can be defined easily on any object

Here is a sample code that demonstrates adding a new method:

import java.util._ // static import

class IntUtil(number: Int) {
   def days = this
   def ago = {
      var cal = Calendar.getInstance()
      cal.add(Calendar.DAY_OF_MONTH, -number)
      cal.getTime()
   }
}

val num = 2
val obj = new IntUtil(num)
println(obj.days.ago)
  • Scala has no primitive types, everything is an object.
  • New methods can be easily added using "implicit conversion"

Here is a code sample that shows how to perform "implicit conversion" and add a new method to a "val"

import java.util._ // static import

class IntUtil(number: Int) {
   def days = this
   def ago = {
      var cal = Calendar.getInstance()
      cal.add(Calendar.DAY_OF_MONTH, -number)
      cal.getTime()
   }
}

val num = 2
val obj = new IntUtil(num)
println(obj.days.ago)

// implicit conversion - only one conversion can be applied per object (or class??)
implicit def pleaseConvertInt2WonderfulIntUtil(number: Int) = new IntUtil(number)

println(2.days.ago)
  • To create Singleton, use the word "object" such as:
class Car {
}

object Car {
    // place all the static methods here
}
  • This singleton object is also called the "companion" object and it must exist in the same file as the original object.
  • Companion object is used to create the factory pattern.
  • Adding "private" to the class definition makes the constructor private.
  • "apply" is a special method: "blah.apply(something)" is equivalent to "blah(something)"
  • "apply" has a cousin "update" and takes 2 parameters

Here is a code that demonstrates some of the above mentioned features:

import scala.collection.mutable._

class Pen private (val color: String) {
    println(color + " pen being created")
}

// companion object - singleton
object Pen {
    val pens : Map[String, Pen] = Map()
    def createPen(color: String) = {
        if (!pens.contains(color))
            pens(color) = new Pen(color)
            // == pens.update(color, new Pen(color)
        pens.get(color)
    }
}

val bluePen = Pen.createPen("blue")
val bluePen2 = Pen.createPen("blue")
val redPen = Pen.createPen("red")

Running this code shows that "blue" pen is created only once and cached during second attempt. Notice, how the Pen is created using "createPen" factory method. This code can be changed to use "apply" as:

import scala.collection.mutable._

class Pen private (val color: String) {
    println(color + " pen being created")
}

// companion object - singleton
object Pen {
    val pens : Map[String, Pen] = Map()
    def apply(color: String) = {
        if (!pens.contains(color))
            pens(color) = new Pen(color)
        pens.get(color)
    }
}

val bluePen = Pen("blue")
val bluePen2 = Pen("blue")
val redPen = Pen("red")

Notice how default constructors instead of the factory pattern are now used.

Here is a piece of code that has two classes with similar functionality:

class Human(val name: String) {
 def listen = println("I am " + name + " your friend")
}

class Animal(val name: String)

class Dog(override val name: String) extends Animal(name) {
 def listen = println("I am " + name + " your friend")
}

val peter = new Human("Peter")
peter.listen

val rover = new Dog("Rover")
rover.listen

This violates the DRY principle. Scala Traits allows to encapsulate the code as shown below:

trait Friend {
 val name: String
 def listen = println("I am " + name + " your friend")
}

class Human(val name: String) extends Friend

class Animal(val name: String)

class Dog(override val name: String) extends Animal(name) with Friend

val peter = new Human("Peter")
peter.listen

val rover = new Dog("Rover")
rover.listen


// include trait at an object level
class Cat(override val name: String) extends Animal(name)

val molly = new Cat("Molly") with Friend
molly.listen
  • XML processing is a first class citizen in Scala
val xml = therethere
println(xml)

// XPath query
println(xml \\\\ "@greet")
println(xml \\\\ "where")
val stock = Map("APPL" -> 250, "GOOG" -> 300)

def createStock() = {
 stock.map { entry =>  }
}

// Scala code within XML
val xml = { createStock() }

println(xml)

Here is the last exercise from the workshop: Use Yahoo Weather API to find the temperature of Denver, CO:

import scala.xml._
import scala.io._
import java.net._

val theURL = "http://weather.yahooapis.com/forecastrss?w=2391279&u=f"

val xmlString = Source.fromURL(new URL(theURL)).mkString
//println(xmlString)    // for debugging

val xml = XML.loadString(xmlString)

val city = xml \\\\ "location" \\\\ "@city"
val state = xml \\\\ "location" \\\\ "@region"
val temperature = xml \\\\ "condition" \\\\ "@temp"

println("Temperature in " + city + ", " + state + " is " + temperature)
  • Actors enable concurrency in Scala, "receive" is used to receive the response from each Actor
  • Don't use "receive" outside, use receive within
  • OK to share Java code within Scala only if its mutable
  • Scala has "tuples", are immutables, and really good candidate for concurrency

Here is a sample code refactoring the above code in a method, called 50 times in a loop, printed once using traditional method invocation and once using Actors. The total time taken for the two set of executions is then printed.

import scala.xml._
import scala.io._
import java.net._
import scala.actors._
import Actor._

def getTemperature(woeid: Int) = {

    val theURL = "http://weather.yahooapis.com/forecastrss?w=" + woeid + "&u=f"

    val xmlString = Source.fromURL(new URL(theURL)).mkString
    val xml = XML.loadString(xmlString)

    val city = xml \\\\ "location" \\\\ "@city"
    val state = xml \\\\ "location" \\\\ "@region"
    val temperature = xml \\\\ "condition" \\\\ "@temp"

    (city, state, temperature)      // tuples are immutable
                                    // good candidates for concurrency
}

val start = System.nanoTime
for (woeid <- 2391250 to 2391299) {
    println(getTemperature(woeid))
}
val end = System.nanoTime
println("Time taken (without Actor): " + (end - start)/100000000.0) 

// Now dispatching to multiple actors
val start2 = System.nanoTime
val caller = self               // self is a pointer to my actor
for (woeid <- 2391250 to 2391299) {
    actor { caller ! getTemperature(woeid) }      // Dispatch 50 actors
}

for (woeid <- 2391250 to 2391299) {
    receive {
       case msg => println(msg)
    }
}
val end2 = System.nanoTime

println("Time taken (with Actor): " + (end2 - start2)/100000000.0)

A sample result from running this script showed the results:

Time taken (without Actor): 171.62816
Time taken (with Actor): 29.05179

As you can see the difference is quite evident - approx 6x better performance when using Actors.

Overall, super excited after writing so much Scala code and learned something new.

Thank you Venkat for yet another great workshop!

Technorati: conf uberconf scala java workshop

About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today