Friday, September 20, 2013

Producer -- Consumer in Groovy

Last days, I've got a feeling that is time to learn some new in programming languages domain and I started to work with Groovy and even if it has problems with encapsulation, I liked a lot the idea. You can write a very light and clean code if you are not trying to create a strange combination between Java and Groovy. Another great thing related to Groovy is that Grails is based on Groovy, and Grails is really awesome.

So, let's start with a very basic example of multi-threading...a producer consumer implementation in Groovy in a classical way, with threads and synchronized blocks of code

**Producer class

class Producer {
 def name
 def products=[]
 private def Object lock;

 def Producer(name,products) {
  this.name = name;
  this.products=products
 }
 
 def produce()
 {
  def i=0
  synchronized (this.lock) {
   
   println this.name + " starting to produce"
   
   while(true)
   { 
    if (this.products.size()==2)
    {
     println this.name+" full stock, so wait"
     
     this.lock.notify()
     this.lock.wait()
     
     println this.products.size()+" more integers please"
    }
    else
    {
     i++
     this.products.add("product "+i)
    }
    
   }
  }
 }
}


**Consumer class

class Consumer {
 def name
 def products=[]
 def Object lock;

 def Consumer(name,products) {
  this.name = name;
  this.products=products
 }
 
 def consume()
 {
  synchronized (this.lock) {
   println ""
   println this.name + " starting to consume"
   while(true)
   {  
    sleep(2000)
    if (this.products.size()>0)
    {
     def index=this.products.size()-1
     println this.name+" consume "+this.products[index]
     this.products.remove(index)
     println "remains "+this.products.size()
    }
    else
    {
     println "is time for more integers"
     this.lock.notify()
     this.lock.wait()
    }
    
   }
  }
 }
}


**And the main program which is the factory, the supermarket or something like this:). Of course for these example I am producing only some integers, not potatoes
class MainApplication {

 static main(args) {
 
  println "Hello world"
  
  def products=[]
  
  def a=new Producer("Producer",products)
  
  def lock=new Object();
  
  def b=new Consumer("Consumer", products)
  
  a.lock=lock
  b.lock=lock
  
  def prodthread=Thread.start {
   a.produce() 
  }
  
  
  def consThread=Thread.start {
   b.consume()
  }
  
 }

}



Note: I'm not setting the lock object within the constructor, because i wanted to show you that private is just a simple word for the moment. This is a problem, but we can live with it right now... OOP, Java, groovy, producer consumer, grails, java frameworks, java language, groovy tutorial

2 comments:

  1. Daily deals provide numerous benefits for the consuming public. First of all, a discount deal gives better opportunities for you to save money. daily deals

    ReplyDelete