Yakov Fain's Blog

My notes about everything in IT

Programming to Interfaces in Java

leave a comment »

Seasoned Java programmers are programming to interfaces. What does it means?

Let’s consider a simple example. Let’s say I’ve declared a variable customers of type ArrayList:

ArrayList<Customer> customers = new ArrayList<>(3);

While this code is correct,  there a better way of declaring the variable customers:

List<Customer> customers = new ArrayList(3);

You can read the first example as follows: “I want to declare a variable customers that will have all access to all API offered by the class ArrayList“. The second version means the following: “I want to declare a variable customers that has a behavior declared in the List interface”. The first example declares a variable of a specific implementation of the List interface – ArrayList. Now rake a look at this code example:

ArrayList<Customer> customers = new ArrayList<>(3);

// The code to populate customers with instances of 
// Customer is omitted for brevity

int totalElem = customers.size();

// Iterate through the list customers and do something with each
// element of this collection

for (int i=0; i<totalElem;i++){
    Customer currentCustomer= customers.get(i);
    System.out.println(currentCustomer);
  }
}

ArrayList implements several interfaces besides List, which means that it has more methods that the List defines.  But if you read the documentation on the List interface, you’ll see that among others it includes the methods as add(), get(), and size() , which are the only ones used with our collection customers. If this is all we need, declaring a variable customers of type List gives us more flexibility. If later we decide to switch to a different implementation of the List (e.g. LinkedList instead of ArrayList ) we won’t need to change the type of the variable customers.

You may say that changing a variable declaration from ArrayList to LinkedList it’s not a big deal – it’s still the same line of code. But it may be a bigger deal if, say you program needs to pass the object referred by customers to another object’s method that also was declared with the argument of type ArrayList:

processCustomers (ArrayList<Customer> customers){

...
}

Now we need to change both the variable and the method argument declarations . In large projects such a refactoring may become a time consuming process.

If you just need a behavior defined in a particular interface (e.g. List), declare the variable of this interface type rather than of a concrete implementation (e.g. ArrayList) of this interface.

P.S. Here’s the Java 8 way of writing the above loop, which is not relevant for the blog subject:

customers.forEach( customer -> System.out.println(customer));

Written by Yakov Fain

October 26, 2014 at 2:34 am

Posted in java

Tagged with

Java Programmers-Terrorists

with 4 comments

Java has a pretty powerful mechanism of error handling. But sometime programmers ignore it. Recently I’ve seen the following post in one of the production support chat rooms:

Developers, please don’t do this:

 } catch (IOException e) {
     //do nothing, just ignore it
 } finally {

this is better:

 } catch (IOException e) {
      logger.error(e,e);
 } finally {

The poster of this message has demonstrated what being overly polite means. I’m not as polite as the guy who wrote this and want to say that Java developers who quietly ignore exceptions should be tracked down and fired. They can be considered terrorists who plant time bombs into applications.

Handling programming errors is a must. Writing an empty catch clause is the worst thing that could be done. It’s like a time bomb that will definitely blow the program up one day, and finding such bombs is usually a time consuming process. Some people want to save a couple of seconds required to log the error, which eventually will cost dearly to the QA and support teams. Don’t cut corners, exception handling should be taken very seriously if you consider yourself a professional software developer.

Written by Yakov Fain

October 24, 2014 at 4:01 pm

Posted in java

Tagged with

Java is short for JavaScript. Not!

with one comment

Here’s  is a quote from the About page  of the Web site ehow.com: “eHow is your one-stop online resource for life’s challenges. Professionals in every field come together to offer expert advice, backed by the additional support of a can-do eHow community.

Experts are also human beings and sometimes they make mistakes too. But when I’ve read the following article I was stunned:

javaisjavas

Guys and girls, I’m not an eHow-grade expert, but I’ve been doing both Java and JavaScript for while. Trust me, the above description is absolutely wrong! Please ignore. Also, if you know any of the 35 people who found this helpful, get in touch with them and tell them the truth!

There is well known statement that “Java is to JavaScript as ham is to hamster”. So I’m looking forward to a new article at eHow that will be a creative interpretation of the Wikipedia definition:

“Hamster, aslo known as ham for short, is processed pork foodstuff, which undergoes preservation through curing, smoking, or salting. Hamsters are traditionally made only from the hind leg of swine, and referred to that specific cut of pork.”

Written by Yakov Fain

October 12, 2014 at 2:18 pm

Posted in java

Tagged with ,

GlassFish, Open MQ, and the Ear-Eye Problem

with one comment

Yesterday I’ve been updating code examples for the messaging chapter for the 2nd edition of my Java book. While doing this, I ran into an issue, then fixed it, but the cause and the solution illustrate the situation that we call “Ear-Eye”, which comes from and old joke popular in the USSR, where TV propaganda was stating that everything is great while people had hard time finding food in store. Here’s the joke:

An old lady comes to a medical center saying that she needs to see an Ear-Eye specialist. The receptionist replied, “There is no such specialization in medicine. Why would you need such a doctor?” The old lady answered, “What I hear on the radio, I don’t see in the real life.”

In programming, we have similar situations quite often – you look at the code everything looks perfect, but it doesn’t work no matter how long you look at it. In such cases you should call a colleague simply saying “I got an Ear-Eye problem”. An extra pair of eyes usually helps. After looking at the monitor for half an hour, I realized that I got an Ear-Eye situation, but it was not a one piece of code, but required a two server setup so it was not a quick thing for explain to a colleague. Eventually, I fixed it myself and am happy to share my story with you.

I’ve been using Java GlassFish 4.1 as an application server, and Open MQ 5.1 as a JMS provider. You can use Open MQ separately, but it’s conveniently bundled with GlassFish. While most of the JMS code samples show how to send/receive messages from Java EE clients using JNDI, it may give novice Java developers a false feeling that this is the only way to do messaging.

So I updated my old code samples to illustrate how to use JMS 2.0 goodies in standalone clients talking directly to Open MQ server. Started Open MQ from the command line with the imqbrokerd script, configured the queue, tested the sender and receiver and all worked as the doctor ordered (no, not that doctor). For those, who are not in the know, Open MQ runs on port 7676 by default. Here’s my standalone JMS sender:

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

   ConnectionFactory factory;
	 
   factory = new com.sun.messaging.ConnectionFactory();  

	try( JMSContext context = factory.createContext("admin","admin")){

		factory.setProperty(ConnectionConfiguration.imqAddressList,
                                        "mq://127.0.0.1:7676,mq://127.0.0.1:7676");
		      Destination ordersQueue = context.createQueue("TradingOrdersQueue");	  
	          JMSProducer producer = context.createProducer();
	      
	          // Send msg to buy 200 shares of IBM at market price	      
	          producer.send(ordersQueue,"IBM 200 Mkt");
	          
	          System.out.println("Placed an order to TradingOrdersQueue");
	                    
	 } catch (JMSException e){
	           System.out.println("Error: " + e.getMessage());
	 } 
 }		
}

And this is the standalone receiver:

public class DirectObjectMessageReceiver implements MessageListener{

	ConnectionFactory factory = new com.sun.messaging.ConnectionFactory();  
	JMSConsumer consumer;
	
	DirectObjectMessageReceiver(){
		try( JMSContext context = factory.createContext("admin","admin")){
			factory.setProperty(ConnectionConfiguration.imqAddressList(
                               "mq://127.0.0.1:7676,mq://127.0.0.1:7676");
		    
			Destination ordersQueue = context.createQueue("TradingOrdersQueue");	  	        
			consumer = context.createConsumer(ordersQueue);
		    
			consumer.setMessageListener(this);
		      
		      System.out.println("Listening to the TradingOrdersQueue...");
		      
		      // Keep the program running - wait for messages
		      Thread.sleep(100000);
		    
		   } catch (InterruptedException e){
	           System.out.println("Error: " + e.getMessage());
	       }
		    catch (JMSException e){
		           System.out.println("Error: " + e.getMessage());
		    } 
	}

    public void onMessage(Message msg){
    	
      try{
       System.out.println("Got the message from TradingOrdersQueue: " +
                          msg.getBody(Order.class));
       
       System.out.println("\n === Here's what toString() on the message prints \n" + msg);
       
      } catch (JMSException e){
    	  System.err.println("JMSException: " + e.toString());
      }
    }

 public static void main(String[] args){
	  new DirectObjectMessageReceiver();
 }	 
}

As you see, the code is has several lines specific to Open MQ implementation, which is not great, but gives me a segway to explain the benefits of JNDI and resource injection. Then I explained how to map GlassFish JNDI queue name to a physical queue in the Open MQ server. So here’s the servlet that serves as a JMS sender, and the JNDI name OutgoingTradeOrders is mapped to a physical queue named TradingOrdersQueue.

@WebServlet("/MessageSenderServlet")
public class MessageSenderServlet extends HttpServlet {
	
	  @Resource(lookup ="java:comp/DefaultJMSConnectionFactory")  // JNDI name
	  ConnectionFactory factory;
	  
	  @Resource(lookup = "OutgoingTradeOrders")  // JNDI name
	  Destination ordersQueue;

	  
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			  throws ServletException, IOException{	
		
		try( JMSContext context = factory.createContext("admin","admin")){
  
		   JMSProducer producer = context.createProducer();
		      
		   // Send msg to buy 200 shares of IBM at market price	      
		   producer.send(ordersQueue,"IBM 200 Mkt");
		          
		   System.out.println("Placed an order to OutgoingTradeOrders");
	  }
	}
}

Got my Open MQ server running, then deployed the servlet and started GlassFish. The servlet obediently sent a message to the queue OutgoingTradeOrders. Basically, I wanted to implement the following workflow:

figure_30-10

The rest seemed to be easy – I wanted to run my standalone message receiver against the Open MQ server to prove that it’s getting messages from TradingOrdersQueue. Started the receiver, it printed “Listening to the TradingOrdersQueue…” and nothing else. Where is the message that the servlet sent? Is there something wrong with the queue names mapping? Started the Open MQ admin console – looks good, the TradingOrdersQueue is there. Started GlassFish Admin Tool – the OutgoingTradeOrders is properly mapped to TradingOrdersQueue.

Then I decided run the servlet again to send a second message to the queue. Maybe the first message got stuck somewhere and the second one would push it out? Nope, no miracles. Tested again the standalone sender and the receiver – work fine. But where are the servlet’s messages?

What would you do in this situation? Correct, it’s time to take a peek into the queue from the servlet’s code to see if is anybody there. Added QueueBrowser to the servlet, which properly showed me the messages sent by the servlet – they were sitting nicely next to each other in the OutgoingTradeOrders queue. Man!

Added the QueueBrowser to the standalone message receiver – the TradingOrdersQueue is empty. What next? I knew this was an Ear-Eye case, but still it would be nice if I could have blamed someone, wouldn’t it? Should I open a ticket at the GlassFish JIRA? Or is it an issue of Open MQ?

Later. I decided to walk my doggy (his name is Sammy) out. During the walk I was thinking about that case when two group of workers started building a tunnel from both sides of the river hoping to meet in the middle, but built two tunnels instead. When I came back, I decided to see if there is something fishy with the port numbers.

I have the only distribution of GlassFish which has the only subdirectory called mq, where the Open MQ software resides. So in both cases (imqbrokerd and GlassFish) I’d be starting the same instance of the Open MQ server, right? Wrong! While imqbrokerd starts it on port 7676, GlassFish start the embedded OpenMQ on port 27676, which is not written in their admin guides. If found a system variable JMS_PROVIDER_PORT deep inside in the GlassFish file glassfish/domains/domain1/config/domain.xml!

This was a situation with tho tunnels! The standalone clients were sending messages to the server running on port 7676, while the servlet was pumping messages to the Open MQ instance running on the port 27676! After changing the port from 277676 to 7676 everything started working!

I would have caught this bug a lot faster, but the GlassFish Admin console was showing me the physical queue TradingOrderQueue that I configured on the server running on port 7676! That’s why I was sure that I was working with the only instance of Open MQ. This is clearly a design flow in the GlassFish Admin Console – instead of showing the physical queues by actually connecting to the Open MQ server, they just read if from the config file.

Anyway, the Ear-Eye issue is resolved. That’s all folks.

Written by Yakov Fain

October 9, 2014 at 9:05 pm

Posted in java

The Dark Side of Google’s HR

with 16 comments

Typically, the conversations that involve Google’s hiring process revolve around the cool questions during technical interviews. Something like, “How many piano tuners are in San Francisco?” Business Insider even published and article titled “15 of Google Interview Questions That Will Make you Feel Stupid”.

But Google’s HR made me feel stupid in a different way. I’m one of the partners of a small consulting company Farata Systems. Some time ago we’ve received a request from another company (let’s call it XYZ) to bid on an interesting project. We won the project competing with two larger bidders. The project started. Our software developers were doing a good job. The XYZ’s team lead praised our job.

Last year Google acquired XYZ, and one of our employees (let’s call him Alex) continued working on this project as a consultant. When we hired Alex, he signed the offer letter with a typical clause that he’s not allowed to work directly for Farata’s clients for the period of 12 month after terminating the employment with us. Previously Alex signed an agreement that had a clause about typical two week notice.

A couple of months ago, the Google’s HR employee approached us asking if they could hire Alex directly – they really like him. No wonder, Alex has excellent technical skills. The HR worker from Google offered us a certain compensation for such conversion, which is also a typical practice between the IT vendors and their clients. There were phone conversations too. We’ve rejected their initial offer and responded explaining how they can keep Alex on the project.

About a month ago, on Friday, we’ve received an email from Alex stating that this was his last day with Farata. No two week notice. He just left and stopped answering phone calls or emails. The team lead from Google didn’t respond to our attempt to contact him either. The Google’s HR person keeps silence as well.

Now I have an easy question for you, “Guess where Alex works now?” You got it! He works at Google, we know it for sure.

We have not decided yet, if we want to take any legal actions against Google, but this experience left a really bad taste in my mouth. Knowing how many piano tuners live in SF is important, but there are some rules in IT that professionals should respect.

Written by Yakov Fain

September 3, 2014 at 6:25 am

Posted in Uncategorized

JCrete 2014

leave a comment »

I spent the last week in the beautiful island of Crete. It was my second JCrete unconference. Last year I was blogging each day and you can see all these blogs here.

This year JCrete was as good as always. Geertjan Wielenga wrote a detailed report here.

Special kudos to Stephen Chin. Here’s his awesome photo of all unattendees. He also recorded a bunch of videos with unattendees of JCrete (myself included), and you can enjoy them at http://nighthacking.com/category/jcrete2014.

My hat off to Uros Djunisijevic who’d never leave his room without  a camera, and you can see lots of JCrete photos here.

This event doesn’t need any promotions – the number of people on the wait list is the same as the number of attendees. JCrete is and will remain successful because the attendees are either seasoned software developers or are eager to learn from others.

But for me, the atmosphere is most important part of this event. Everyone is friendly and is willing to discuss whatever is on your mind. There are no official speakers. Everyone is accessible and willing to share.

After participating in JCrete unconferences I know who’s doing what. If I need to find an answer to a question on a particular Java-related technology, I know who to ask. Networking at its best. And no, I’m not talking about people who can give me work. This is networking of people in the know.

But more importantly, this is probably the best vacation a Java developer can think of. Three hours of session a day followed by relaxing at the great beaches while continuing professional discussions with respected people. This works perfectly for me.

photo (60)

I hope to be able to come to each of the future JCrete unconferences if circumstances permit. I also hope to be able to organize a similar event in the city of Odessa, Ukraine next summer. But I don’t want it to be limited only for Java developers. In 2015 the words “I’m a senior Java developer” will sound like “I’m a master of a Phillips screwdriver”. Modern programmers needs to know several programming languages, don’t they?

Written by Yakov Fain

August 31, 2014 at 8:33 pm

Posted in Uncategorized

Blood Pressure While Presenting at Conferences

with 5 comments

In June I was presenting at the ThingsExpo conference  at Javits Center in New York City. During my talk I was demonstrating how to integrate consumer devices into a business workflow (we develop software for insurance agents). In particular, I was doing live measuring of my own blood pressure to show how to integrate consumer devices into a business workflow. Internet of Things, you know. The results were automatically appearing in my customized Web application.

When the results appeared on my mobile device I was quite surprised to see that my pressure was 200/120. This was damn high. My regular blood pressure is typically around 140/90. If you think that presenting in front of a large group of people makes me stressed out, this is not the case. I’m pretty experienced speaker and, actually enjoy presenting. I thought that was a device failure.

.bloodpressure

I’m writing this blog from the beautiful Crete Island, Greece. As you see, on August 28 at 5:45AM my blood pressure is normal. I’m participating in a small conference called JCrete – this is where experienced Java developers unwind.

Guess what, I was delivering a scaled down version of the same presentation in a small room in front of a dozen people. The atmosphere in the room is friendly and relaxed. May be that’s the reason why the results of my blood pressure measurement where not as high as in New York: 180/110. It’s still pretty damn high. Again, I was not nervous at all. Yes, I was a little excited.

This make me wondering if talking from the podium increases blood pressure? In October I’ll be measuring my pressure on stage at the conference in Moscone Center in San Francisco. I’ll update this blog with fresh numbers then.

Is presenting at a conference dangerous for your health? Should people with high blood pressure avoid public speaking?

If you know of some scientific studies of this subject please leave a comment on this blog. If you are a speaker yourself, do a little experiment – take a blood pressure monitor with you next time you’re presenting. Do the measurements immediately after your talk is over. Don’t be ashamed. Let’s contribute to medical science.

Written by Yakov Fain

August 28, 2014 at 3:55 am

Posted in Uncategorized

Tagged with

Follow

Get every new post delivered to your Inbox.

Join 149 other followers