The UUID generator in Scala

After I was done with the multi-threading test of the UUID generator, I tried to develop a Scala version, since I am learning it and specially interested in the Actors model (I think that is the major attraction to java developers)

Here is what I have:

import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
import java.util.UUID
import scala.actors._
import scala.actors.Actor._
import scala.collection.mutable.Queue

object UniqueIdGenerator{
  val uuids  = new Queue[UUID] //new LinkedBlockingQueue[UUID]()

	 populate();

	def getId: UUID = {
	  //val id = uuids.take()
	  val id = uuids.dequeue
	  //repoulate if empty
	  if(uuids.size==0){
	    populate()
	  }
	  return id
	}

	def populate() = {
	  println("populating...")
	  for( i <- 1 to 1000){
		//uuids.put(UUID.randomUUID())//
	    uuids.enqueue(UUID.randomUUID())
	  }
	}
}
object UniqueIdGeneratorActor extends Actor{

	def act(){
	  var consumerDone=0
	    loop {
		    react{
		      case (requester:Actor) =>
		        requester !  UniqueIdGenerator.getId
		      case "ConsumerDone" =>
		        consumerDone = consumerDone+1
		        if(consumerDone==100){
		        	println("I am done too")
		        	exit()
		        }
		    }
	  }
	}
}

class IdConsumer(name:String) extends Actor{
  def act(){
    var i=0
    println(name + " started")
    UniqueIdGeneratorActor ! (self)
    loop {
     react{
       case "EXIT" =>
         UniqueIdGeneratorActor ! "ConsumerDone"
         println(name + " was shutdown")
         exit()

       case msg =>
         i=i+1
         if(i==1000){
           UniqueIdGeneratorActor ! "ConsumerDone"
           println(name + " is done")
        	exit()
         }else{
           UniqueIdGeneratorActor ! (self)
         }
     }

    }
  }
}

object TestApp2 {
  def main(args : Array[String]) : Unit = {
	println("started")
	UniqueIdGeneratorActor.start()
	for(i <- 1 to 100){
	  val consumer = new IdConsumer("consumer" + i)
		consumer.start()
	}
  }
}

This is not exacly a replicate of the Java version – I had to explicitly create a “UUID generator producer” actor to listen and serve the UUID requets. I’d like to eliminate the producer and make the scala version just as the java one. My understanding is the concurrency programming in Scala is basically through messaging. So, when one actor happens to find the queue is empty, it will need to communiate to the other actors to let them know.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s