Yakov Fain's Blog

My notes about everything in IT

Closures in Java With Lambdas

with 2 comments


While working on the second edition for my Java 24-hour Trainer book I’m re-writing some of the code samples to use lambda expressions. Today I was re-writing an example for wait/notify for the chapter on multi-threading. Beside illustrating the wait/notify, I used a closure in this example. Since Java closures are not well presented in the blogosphere, I decided to write a quick blog on the subject.

My goal was to write a program that starts a thread and waits for the notification from that thread until its execution is completed. When the main thread receives the notification from the second thread it continues processing.

In the traditional object oriented programming you’d create a class that implements Runnable with a constructor receiving an object to send notification to, for example:

class MarketNews implements Runnable throws InterruptedException{
    Object parent;
    
    MarketNews(Object whoToNotify){
        parent=whoToNotify;
    }

    public void run(){
       // Do something
       synchronized(parent){
           parent.notify();
       }
    }
}

Turning Runnable into a lambda expression and creating a thread is simple:

  Runnable mNews = () -> {
	// Do something
        // But who to notify????
  }; 
   
  Thread marketNews = new Thread(mNews, "Market News");
  marketNews.start();

But how to let the mNews know who to notify when this “Do something is done?” How to pass the reference to that parent thread? It’s not overly difficult if you understand the concept of closures and know that a method can return lambda expression.

In functional languages like JavaScript a closure is a nested function that knows the context where it was declared (I know, it’s fuzzy, just bear with me). In Java there is not nested function but you can return a lambda expression from a method:

private Runnable getMktNewsRunnable(){
   return () -> {//Do something};
}

Runnable mktNewsRunnable = getMktNewsRunnable();

After running the above code the variable mktNewsRunnable will store the text of the lambda expression that can be used for creating a thread:

new Thread(mktNewsRunnable, “Market News”).start();

But this version of lambda expression still doesn’t know who to notify. Let’s fix it:

private Runnable getMktNewsRunnable(Object whoToNotify){
   return () -> {
      // Do something
      // whoToNotify.notify();
   };
}

Runnable mktNewsRunnable = getMktNewsRunnable(this);

I’m using the fact that when the closure was created by the above return statement, it knew about the existence of the variable whoToNotify in the neighborhood! The rest is easy – just put the call to notify() into the synchronized block to make the Java compiler happy. Here’s the complete working example.

public class TestLambdaWaitNotify {

  private static Runnable getMktNewsRunnable(Object whoToNotify){
      
	return  () -> {
		 try{
	      for (int i=0; i<10;i++){
	       Thread.sleep (1000);  // sleep for 1 second
	       System.out.println( "The market is improving " + i);
	      } 
	      
	      synchronized(whoToNotify){
	          whoToNotify.notify(); // send notification to the calling thread	   
	       }
	    }catch(InterruptedException e ){
	       System.out.println(Thread.currentThread().getName() 
	                                        + e.toString());
	    }  
	};    
  }
	
	
  public static void main(String args[]){
    	
	 TestLambdaWaitNotify thisInstance = new TestLambdaWaitNotify();
	 
	 Runnable mktNewsRunnable = getMktNewsRunnable(thisInstance);
	 Thread marketNews = new Thread(mktNewsRunnable,"");
	 marketNews.start();
   
     
     synchronized (thisInstance) {
    	   try{
    		   thisInstance.wait(20000);  // wait for up to 20 sec
    	   } catch (InterruptedException e){ 
    		   e.printStackTrace();
    	   }
    	 }
     
        System.out.println( "The main method of TestLambdaWaitNotify is finished");
  }
}

The main thread will print the message “The main method of TestLambdaWaitNotify is finished” only after receiving the notification from Runnable or when 20 sec expires. Easy?

If you want to see how to write closures in JavaScript, I’ll be running a JavaScript Webinar for O’Reilly on Aug 5th.

About these ads

Written by Yakov Fain

July 21, 2014 at 9:29 pm

Posted in java

2 Responses

Subscribe to comments with RSS.

  1. Yakov,

    If your example is asynchronous producer/consumer tutorial then You are gaming the timing issues with a long enough delay. In the general case it is necessary to use some kind of condition (” data readiness”) to wait for. Let me suggest BlockingQueue/CompletableFuture/CountDownLatch for this task – any of them hides complexity associated with low-level synchronization primitives and makes code’s author intents more clear.

    Valery

    July 22, 2014 at 6:49 pm

    • I know, but the goal of this blog was to show an example of using closures. Discussing other issues would unnecessary complicate this blog.

      Yakov Fain

      July 22, 2014 at 7:17 pm


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

Follow

Get every new post delivered to your Inbox.

Join 146 other followers

%d bloggers like this: