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.

Written by Yakov Fain

July 21, 2014 at 9:29 pm

Posted in java

Working on the second edition of Java Tutorial

with 2 comments

In 2011 Wiley (Wrox) published my book “Java Programming. 24-Hour Trainer“. To be honest, I don’t like the title because it misleads people as if this book promises that the reader can learn Java within 24 hours. But creators of this series (many titles were published under this umbrella) meant to say that this book was like your personal instructor; 24 hours a day. Whatever. It’s not my call.

But earlier this year I got a call from the publisher stating that they’re happy with the book sale numbers and want me to update the book and release the second edition reflecting the latest changes in the Java Language.

I agreed because with the latest release Java became more interested than ever. The magnitude of changes to the Java 8 language and APIs can be compared with Java 5 that was released back in 2004. It’s exciting to program in Java again.

In the second edition I’m replacing Java applets chapters with JavaFX . The Java EE part will reflect the latest Java EE edition. Of course, I’m adding the coverage of lambdas and Stream API. Re-writing and simplifying all examples and testing them in the freshly released Eclipse Luna IDE. GlassFish 4 is my server of choice for all Java EE 7 examples.

Those of you who used the first edition of my book or watched my Intro To Java video lessons may start using the fresh version of code examples, which I started publishing on Github. So far I’ve I’ve uploaded examples for lessons 1-10 and 13-17. If you haven’t worked with git, watch this video to get up to speed. I’d really appreciate your feedback on these code samples. The Table of Contents of the second edition is shown below.

1. Introducing Java
2. Integrated Development Environment
3. Object-Oriented Programming with Java
4. Class Methods and Constructors
5. Java Syntax: Bits and Pieces
6. Packages, Interfaces, and Encapsulation
7. Programming with Abstract Classes and Interfaces
8. GUI Basics with Swing
9. Event Handling in Swing GUI
10. Error Handling
11. GUI Basics with JavaFX
12. Developing a game with JavaFX
13. Collections
14. Generics
15. Lambda Expressions and Functional Programming
16. Working with I/O Streams
17.Java Serialization
18. Network Programming Basics
19. Introduction to Concurrency
20. The Stream API
21. Working with Databases Using JDBC
22. Rendering Table Data to GUI
23. Annotations and Reflection
24. Remote Method Invocation
25. Java EE 7 Overview
26. Programming with Servlets
27. JavaServer Pages
28. Web Applications with WebSockets
29. Java Messaging Service
30. Java Naming and Directory Interface
31. Enterprise JavaBeans
32. Java Persistence API
33. RESTful Web Services With JAX-RS
34. Introduction to Spring MVC Framework
35. Introduction to Spring Security
36.Build Automation with Gradle
37. Java Technical Interviews

Written by Yakov Fain

July 15, 2014 at 8:57 pm

Posted in java

Losing Polymorphism with Java Lambda Expressions

with 8 comments

Yesterday, I decided to re-write with lambdas one of the example I use while explaining polymorphism during my Java trainings. I realize that lambdas promote functional style of programming, while polymorphism is one of the crucial object-oriented features. Still, I decided to try mixing OOP and functional styles to see what happens.

The Task

The class Person has two descendants: Employee and Contractor. Also, there is an interface Payable that’s used to increase pay for workers.

public interface Payable {
   int INCREASE_CAP = 20;
   boolean increasePay(int percent);
}

Both Employee and Contract implement Payable, but the implementation of the increasePay() should be different. you can increase pay to the Employee by any percent, but the Contractor’s pay increase should stay under INCREASE_CAP.

The OOP version

Here’s the class Person:

public class Person {
	private String name;
	
	public Person(String name){
		this.name=name;
	}

	public String getName(){
		return "Person's name is " + name; 
	}
}

Here’s the Employee:

public class Employee extends Person  implements Payable{

   public Employee(String name){
     super(name);
    }
    public boolean increasePay(int percent) {
    System.out.println("Increasing salary by " + percent + "%. "+ getName()); 
    return true;
  }
}

Here’s the Contractor:

 public class Contractor extends Person implements Payable {
	
   public Contractor(String name){
 	super(name);
    }
   public boolean increasePay(int percent) {
	if(percent < Payable.INCREASE_CAP){
	  System.out.println("Increasing hourly rate by " + percent + 
                                      "%. "+ getName()); 
	  return true;
	} else {
	   System.out.println("Sorry, can't increase hourly rate by more than " + 
                       Payable.INCREASE_CAP + "%. "+ getName());
	   return false;
	}
  }
}

Here’s the code that will perform pay increase in a polymorphic way:

public class TestPayInceasePoly {

  public static void main(String[] args) {

     Payable workers[] = new Payable[3];
	workers[0] = new Employee("John");
	workers[1] = new Contractor("Mary");
	workers[2] = new Employee("Steve");		
	
        for (Payable p: workers){
	    p.increasePay(30);
	 }
  }
}

The output of this program looks like this:

Increasing salary by 30%. Person’s name is John
Sorry, can’t increase hourly rate by more than 20%. Person’s name is Mary
Increasing salary by 30%. Person’s name is Steve

Introducing Lambdas

Now I decided to experiment with lambdas. Namely, I wanted to pass a function as an argument to a method. I wanted to extract the increase pay logic from Employee and Contractor into lambda expressions and pass them to workers as argument to their methods.

I left the code of the Payable interface without any changes.

Here’s the new Person class that includes the method validatePayIncrease, which will take a lambda expression as a first argument (passing a function to a method):

public class Person {
	
	private String name;

	public Person (String name){
		this.name = name;
	}
	
	public String getName(){
		return name;
	}
	
	public boolean validatePayIncrease(Payable increaseFunction, int percent) {
			 
         boolean isIncreaseValid= increaseFunction.increasePay(percent); 
         	 
         System.out.println( " Increasing pay for " + name + " is " + 
        	              (isIncreaseValid? "valid.": "not valid."));
		 return isIncreaseValid;
	}
}

The new version of Employee doesn’t implements Payable:

public class Employee extends Person{

  // some other code specific to Employee goes here

  public Employee(String name){
	  super(name);
  } 
}

The new version of Contractor doesn’t implements Payable either:

	  
public class Contractor extends Person{
    

  // some other code specific to Contractor goes here

    public Contractor(String name){
       super(name);
    }
}

Finally, the program that will increase the pay to all workers passing different lambda expressions to employees and contractors.

public class TestPayIncreaseLambda {
	
  public static void main(String[] args) {

        Person workers[] = new Person[3];
		workers[0] = new Employee("John");
		workers[1] = new Contractor("Mary");
		workers[2] = new Employee("Steve");		

	  // Lambda expression for increasing Employee's pay
	   Payable increaseRulesEmployee = (int percent) -> {
				return true;
	   };
	   
		// Lambda expression for increasing Contractor's pay	   
	    Payable increaseRulesContractor = (int percent) -> {
	    	if(percent > Payable.INCREASE_CAP){
	    		System.out.print(" Sorry, can't increase hourly rate by more than " + 
	    	             Payable.INCREASE_CAP + "%. "); 
				return false;
			} else {	
				return true;
			}
	   };	
	   
	   for (Person p: workers){
		   if (p instanceof Employee){
			   // Validate 30% increase for every worker
			   p.validatePayIncrease(increaseRulesEmployee, 30); 
		   } else if (p instanceof Contractor){
			   p.validatePayIncrease(increaseRulesContractor, 30);
		   }
	   }
  }

}

As you see, I’m passing one or the other lambda expression to the method validatePayIncrease. Running this program produces the following output:

Increasing pay for John is valid.
Sorry, can’t increase hourly rate by more than 20%.  Increasing pay for Mary is not valid.
Increasing pay for Steve is valid.

It works, but so far I like my OOP version better than the lambda’s one:

1. In the OOP version I’ve enforced a contract – both Employee and Contractor must implement Payable. In the lambda’s version it’s gone on the class level. On the plus side, the strong typing still exists in the lambda’s version –  the type of the valiastePayIncrease first argument is Payable.

2. In the OOP version I didn’t use type checking, but in the lambda’s version this ugly instanceof creeped in.

While it’s cool that I can pass the function to the object and execute it there, the price seems to be high. Let’s see if this code can be further improved.

Getting rid of the class hierarchy

Currently the code in Employee and Contractor is the same. If the only difference in their code is implementation of the validatePayIncrease method, we can remove the inheritance hierarchy and just add the property boolean workerStatus to the class Person to distinguish employees from contractors.

Let’s get rid of the classes Employee and Contractor and modify the Person. I’ll add the second argument to the constructor workerStatus.

public class Person {
	
	private String name;
	private char workerStatus;  // 'E' or 'C'

	public Person (String name, char workerStatus){
		this.name = name;
		this.workerStatus=workerStatus;
	}
	
	public String getName(){
		return name;
	}
	
	public char getWorkerStatus(){
		return workerStatus;
	}
	
	public boolean validatePayIncrease(Payable increaseFunction, int percent) {
			 
         boolean isIncreaseValid= increaseFunction.increasePay(percent); 
         	 
         System.out.println( " Increasing pay for " + name + " is " + 
        	              (isIncreaseValid? "valid.": "not valid."));
		 return isIncreaseValid;
	}
}

The code of the TestPayIncreaseLambda will become simpler now. We don’t need to store objects of different types in the array workers and can get rid of the instanceof:

public class TestPayIncreaseLambda {
	
  public static void main(String[] args) {

        Person workers[] = new Person[3];
		workers[0] = new Person("John", 'E');
		workers[1] = new Person("Mary", 'C');
		workers[2] = new Person("Steve", 'E');		

	  // Lambda expression for increasing Employee's pay
	   Payable increaseRulesEmployee = (int percent) -> {
				return true;
	   };
	   
		// Lambda expression for increasing Contractor's pay	   
	    Payable increaseRulesContractor = (int percent) -> {
	    	if(percent > Payable.INCREASE_CAP){
	    		System.out.print(" Sorry, can't increase hourly rate by more than " + 
	    	             Payable.INCREASE_CAP + "%. "); 
				return false;
			} else {	
				return true;
			}
	   };	
	   
	   for (Person p: workers){
		   if ('E'==p.getWorkerStatus()){
			   // Validate 30% increase for every worker
			   p.validatePayIncrease(increaseRulesEmployee, 30); 
		   } else if ('C'==p.getWorkerStatus()){
			   p.validatePayIncrease(increaseRulesContractor, 30);
		   }
	   }
  }
}

If a new type of a worker will be introduced (e.g. foreign workers), we’ll just need to add another lambda expression to the class TestPayIncreaseLambda that implements business rules for foreign workers.

The purists may not like the fact that I’m using hardcoded ‘E’ and ‘C’.You can add a couple of final variables EMPLOYEE and CONTRACTOR at the top of this class.

So what’s the verdict? Losing polymorphism may not be a bad thing. The code became simpler, we’ve removed two classes, but didn’t lose the type enforcement (the Payable interface). Software developers that use functional programming languages live without polymorphism and don’t miss it.

P.S. As a matter of fact you can lose the Payable interface too. This would require a different implementation of our lambda expressions with the help of the interfaces from the new package java.util.function. But this should be a topic of a separate blog. OK, here’s a hint: I did it using the BiFunction interface.

Written by Yakov Fain

July 11, 2014 at 3:52 pm

Posted in java

Be all you can be. Facebook.

with 4 comments

If there is one thing I hate about the Internet it’s the damaging effect that social networks like Facebook have on people’s minds.  Some of the younger minds are getting complete out of touch with the real world. They create their image to be seen online as super heros, bad boys, or even criminals. While in the real life, they could be  vulnerable teenagers or young adults  suffering from fear, anxieties, and lacking communication skills. But even 30-year old are losing their minds when get connected.

Yesterday I’ve heard the news on the radio, which is a good example of how far sick minded people can go on the Web. I’m talking about a virtual cannibal. He worked as a New York policeman till his wife found his online communication discussing preparing, cooking and eating his wife. She immediately packed her bags and ran away with their child.

Yesterday this virtual policeman cannibal was released from jail because he didn’t kill or eat anyone. IMO, the laws should be changed and such social-network-virtual-criminals should serve time in prisons for just presenting themselves as killers, robbers, rapers, et. al.

Mark Zuckerberg should buy out the US Army’s motto:

Be all you can be. Facebook.

 

 

Written by Yakov Fain

July 3, 2014 at 1:36 pm

Posted in life, Web

Swing rendering seems to be broken in Java 8

with 12 comments

Here’s a simple Java program that I wrote to test Swing GUI in Java 8 (I use JDK 1.8.0_05-b13):

 

import javax.swing.JFrame;
import javax.swing.JButton;

public class HelloWorld extends JFrame {

public static void main(String[] args) {
JFrame myWindow = new HelloWorld();

// Creating and adding a button the the container
JButton myButton = new JButton (“Click me”);
myWindow.add(myButton);

myWindow.setSize(200,300);
myWindow.setTitle(“Hello World”);
myWindow.setVisible(true);
}
}

The program renders fine on MAC OS:
HelloWorld_java8_MAC

But this is what I get on Windows 7 Ultimate with JDK 1.8.0_05-b13:
HelloWorld_java8_Windows

In JDK 1.7 under Windows it works fine:

HelloWorld_java7_Windows

I’ve asked some people to try the same code with the same version of Java and they don’t see this issue.

I’ve submitted a bug report to Oracle (it’s in review for two weeks), but if you use Java Swing, test your code before migrating to Java 8.

Update.Running this app with the following command-line parameters helped fixing the situation with bad rendering on Windows:
java -Dsun.java2d.opengl=True HelloWorld
java -Dsun.java2d.d3d=false HelloWorld

So the Swing rendering is broken as it should not depend on the external to JVM software.

Written by Yakov Fain

June 27, 2014 at 5:13 pm

Posted in java

Back From Ukraine

with one comment

Last week I was participating in JEEConf – a Java conference in Kiev, Ukraine. It was the fourth annual conference attended by 700 people despite of the unrest on some of the Ukrainian regions. Kiev was quiet, peaceful and nice looking though.

A day before the conference I’ve delivered a presentation at the National Technical University of Ukraine (aka KPI). Only about a hundred of 50 thousands NTUU students were interested to learn about the new features of Java 8. No hard feelings guys. Let’s make it two hundred next year. :-)

The next morning I’ve delivered the same presentation to at least 400 people at the conference, and in the afternoon I ran two consecutive sessions on HTML5 development for about 150 attendees. I’ve included   all these numbers here to draw the attention of the international speakers. Guys, you’re welcomed in Ukraine. There were many international speakers from all over the world this year too. The technical level of the conference is really good.

Due to political reasons the local currency (hryvna) is inexpensive for foreigners, but Kiev offers lots of nice places for sightseeing, has good restaurants, and night clubs. Here’s a photo of one of my dinners there (borshch, salo, vodka, and more):

budam424

 

This was my third consecutive visit to JEEConf, and the conference organizers promised not only to add a large cake to their whiskey party, which is a good reason for me to attend this conference next year!

The photos from Kiev’s conference are here and here. A nice looking guy in black FARATA t-shirt is me.

In June I’m attending the Internet of Things Expo in New York City – I’ll be presenting an approach of integrating little “things” into Java enterprise applications. I’ll be using one of the insurance business workflows. Our team builds software for insurance agents (http://www.surancebay.com), and introducing Internet-powered small devices opens lots of interesting opportunities for us.

In August I’ll be participating in a small unconference in Greece titled JCrete. In the unlikely event you haven’t heard about JCrete, watch this short video.

End of September is the JavaOne time, and Oracle kindly offered free conference passes to Java Champions. I’ve submitted a talk proposal there too. But I’m planning to attend JavaOne even if my talk won’t be accepted. Java is stronger than ever, but having yet another reassurance never hurts.

That’s all, folks. Back to work.

Written by Yakov Fain

May 30, 2014 at 1:51 pm

Posted in IoT, java, JCrete

He calls it rude

with 2 comments

This will be the easiest blog to write because I’ll just copy/paste one of the today’s email threads. I swear, I have not changed a word.

X. Modern Web Application development for Java Programmers: 1) Is this the first iteration of this course? 2) If no, do you have any testimonials from past students that you could share? 3) How often is this course repeated? I’m interested but concerned for my work load when the July course hits it stride. Thanks, X

Me.
1. Third
2. No
3. 4 times a year
4. If you can’t commit 20 hours a week don’t waste your money.

X.  What an offensive response ! I don’t need advice on how to spend my money. I expected you to share the date of the next course so I’d be in a better position to make a decision if July or the next iteration would be better.  You chose instead to be rude and in the process lose what was almost certainly a new customer. 

Me. You call it rude, I call it honest. It’s OK to lose a customer sometimes.

 

Written by Yakov Fain

May 17, 2014 at 2:05 am

Posted in java

Follow

Get every new post delivered to your Inbox.

Join 142 other followers