Friday, September 30, 2011

How to String Split Example in Java - Tutorial

Java String Split Example
I don't know how many times I need to Split String in Java. Split is very common operation given various data sources e.g CSV file which contains input string in form of large String separated by comma. Splitting is necessary and Java API has great support for it. Java provides two convenience methods to split strings first within the java.lang.String class itself: split (regex) and other in java.util.StringTokenizer. Both are capable to split the string by any delimiter provided to them. Since String is final in Java every split-ed String is a new String in Java.

Thursday, September 29, 2011

Top 10 Spring Interview Questions Answers J2EE

Spring framework interview questions is in rise on J2EE and core Java interviews,  As Spring is the best framework available for Java application development and now Spring IOC container and Spring MVC framework are used as de-facto framework for all new Java development. With this popularity interview questions from spring framework is top on any list of  core Java Interview questions. I thought to put together some spring interview questions and answers which has appeared on many Java and J2EE interviews and useful for practicing before appearing on any Java Job interview. This list of Spring interview questions and answers contains questions from Spring fundamentals e.g. Spring IOC and dependency Injection, Spring MVC framework, Spring Security, Spring AOP etc, because of length of this post I haven't included Spring interview questions from Spring JDBC and JMS which is also a popular topic in core Java and J2EE interviews. I suggest to prepare those as well. Any way these Spring questions are not very difficult and based on fundamentals e.g. What is default scope of Spring bean and mostly asked during first round or telephonic round of Java interview. Although you can find answers of these Spring interview questions by doing Google but I have also included some answers for quick reference. As I said Spring  and Spring MVC is fantastic Java framework and if you are not using it than start using it, these questions will give you some head start as well.

Wednesday, September 28, 2011

Top 10 Servlet Interview Question Answers - J2EE

This time its servlet interview questions, I was thinking what to pick for my interview series and than I thought about J2EE and Servlet is my favorite on that space. Servlet is an important part of any J2EE development and serves as Controller on many web MVC frameworks and that’s why it’s quite popular on J2EE interviews. These Servlet questions are based on my experience as well as collected by friends and colleague and they are not only good for interview practice but also shows a new direction of learning for any one who is not very familiar with servlet technology.

Servlet interview question and answerAs said earlier this interview question article is part of my earlier series java interview questions , UNIX command interview questions and Java threading interview questions.

You can find answers of all these questions on google but I have also listed my answers fo r quick reference.

Sunday, September 25, 2011

Finally Eclipse supports JDK7 in Eclipse Indigo 3.7.1

Much awaited release of Eclipse with JDK7 is now over, Eclipse has announce release of version Indigo 3.7.1 which will support JDK7.though I already have downloaded Netbeans with JDK7 support I was eagerly waiting for my favorite java development IDE to comes with java7 support. I am expecting this to support all new java7 features including automatic resource management, string in switch and multiple-cache block in exception handling. You can download the new Eclipse 3.7.1 version from here. You can also update your existing eclipse IDE with new feature from Menu-->Help-->Check for

eclipse with jdk7, eclipse indigo 3.7.1 with java7There is not much in this release except JDK7 feature, no new feature has been introduced which will probably be released in either 3.8 or 4.2. Java community is still embracing JDK7 but sooner or later it will adopt it and my feeling is that it will happen very soon because it contains the similar features which JDK 1.5 was contained though not that significant but still pretty useful for day 2 day work.


Related Java tutorials

Saturday, September 24, 2011

Code Review Checklist and Best practices in Java

What to review while doing Code review
Code Review and Unit testing is one of best development practice I always recommend, strive for and enforce as much as possible. Even just by doing code review and Junit test case always offer positive result it can be improved a lot by constantly learning with our mistakes , others mistakes and by observing how others are doing it. I always try to get my code review by some one with more experience so that I can capture any domain specific scenario which has been missed during think through process and some with less experience so that he can improve his code readability, have a four eye check and most importantly I found that when i explain my code to some one as part of code review I myself discover many things which can be improved or left out.Overall it always add something and improve code quality and reduce bug.

code review checklist, code review best practicesI also review some one else code and voluntary take part to improve my code understanding ability and offer help to others, In this article I will list things which I look while doing code review. These are the things which I have been accumulated over the years but I also look forward to you guys to contribute your experience, best practices for code review and suggest how you guys do code review. These tips are independent of language and equally apply to Java, .NET or C++ code.

10 points checklist on Code Review

1) Does Code meet functional requirement: first and foremost does code meets all requirements which it should met, point out if anything has been left out.

2) Is there any Side effect of this change: Some time one change in your system may cause bug in other upstream and downstream system and it’s quite possible that new developer or anyone who is writing code might not be available of that dependency. This often directly related to experience in project and I found that the more you know about system and its environment better you able to figure this out.

3) Concurrency: does code is thread-safe? Does it have properly synchronized if using shared resource? Does it free of any kind of deadlock or live-lock? Concurrency bugs are hard to detect and often surfaces in production. Code review is one place where you can detect this by carefully understand design and its implementation.

4) Readability and maintenance:  does code is readable? Or is it too complicate for some-one complete new. Always give value to readability as code is not just for this time it will remain there for long time and you need to read it many times. Another important aspect is maintenance as most of software spends 90% time in maintenance and only 10% time on development it should be maintainable and flexible in first place. You can verify that whether code is configurable or not, look for any hard coding, find out what is going to be changed in near future etc.

5) Consistency: This is part of point 4 but I have made it another separate point because of its importance. This is the best thing you can have in your code which automatically achieves readability. Since many developer and programmer take part in project and they have there own style of coding, it’s in best interest of everybody to form a coding standard and follow it on letter and spirit. For example it’s not good someone using function initialize() and other is using init() for same kind of operation, keep you code consistent and it will look better, read better.

6) Performance: Another important aspect most important if you are writing high volume low latency electronic trading platform for high frequency trading which strives for micro second latency. Carefully monitor which code is going to execute at start-up and which is going to be executed in loop or multiple times, optimize the code which is going to execute more often.

7) Exception handling: Ask does code handles bad input and exception? It should and that too with predefined and standard way which must be available and documented for support purpose. I put this point well above on my chart while doing review because failing on this point can lead your application crash and not able to recover from fault on other system or other part of same application.

8) Simplicity: Always see if there is any simple and elegant alternative available at-least give a thought and try. Many times first solution comes in mind is not best solution so giving another thought is just worth it.

9) Reuse of existing code: See if the functionality can be achieved by using existing code, advantage of doing this is that you are using tried and tested code which reduce your QA time and also give you more confidence. Introducing new libraries introduce new dependency. I prefer not to try anything fancy until it’s absolutely necessary.

10) Unit test: Check whether enough JUnit test cases have been written and cover sufficient percentage of new code. never let you pass the code without Junit test because developer often make excuse of time but believe me its worth to write it.

Not last but least that put a comment on your java file that by whom it has been reviewed, what issue finds are out and status of those. This will make the whole process official and ensures that due diligence would be applied during code review. Its also good to maintain your own code review checklist or a project wise code review checklist and use it every time while doing review. There are so many best practices but I have only included those which I follow and found interesting but as I had said earlier this is the area which always needs improvement and no body is perfect on that. So please contribute your ideas on code review and effective development.


Some older post you may like

How to convert String to Date in Java - SimpleDateFormat Example

SimpleDateFormat in Java can be used to convert String to Date in Java. java.text.SimpleDateFormat is an implementation of DateFormat which defines a date pattern and can convert a particular String which follows that pattern into Date in Java.This is the second part of the article on java.util.Date and String in Java. In the first part we have seen How to convert Date to String in Java. SimpleDateFormat accepts a String in any date format e.g. yyyyMMdd is a date pattern and  20110924 is a String in that format. Now you want to create a java.util.Date object from this String. In this Java tutorial we will see list steps to convert String to Date in Java and then we will see different examples of SimpleDateFormat with different date patterns e.g. ddMMyy or dd-MM-yyyy. Though converting String to Date is quite easy using SimpleDateFormat, but you need to remember that SimpleDateFormat is not thread-safe, which means you can not share same instance of SimpleDateFormat between multiple threads. Avoid storing SimpleDateFormat in static variable and if you want to safely share or reuse SimpleDateFormat, you need to make it thread-safe. One way is to use ThreadLocal variable in Java to make SimpleDateFormat thread-safe, as shown in this example.

How to get google plus invites free

google + (plus) invites free

Hi guys as you know that google plus are a new social networking buzzes a google answer to facebook. But it’s different than facebook in terms of joining the site. It’s not open like facebook instead you need invites to join the google plus many of you might be already in google plus but for those who are not yet join google plus I have something to offer.

I have just joined the google plus thanks to my friend who invited me to join google plus and now I have many google plus invites left with me which I would  like to give you , my readers and anyone who is interested to joining google plus. I have been reading on google plus now and seeing how it is different than facebook. One good thing is that it provides more on privacy front and idea of google circle is quite nice. I am sure it will take a lot of time to topple facebook and its definitely a challenge for google but its a good networking service to join.

google plus invitees free

What you need to do to get google plus invites

Just drop your name and email address as comment and I will send you google invites. if you don't want to publish your email then let me know and I won't publish your comment but will send you the invites in your email.


Friday, September 23, 2011

How to write Production quality code?

We often here the term "production quality code" , some times in interview where interviewee asked to write production quality code for a particular function,Some time discussion between developers and programmers and some time during code review. I know most of you familiar with term but for those who wonder what is production quality code in simple terms its code which can bear the test of time in production environment.

We all develop code in development, than test in QA and finally it gets released in production. But there are lot of difference between test and prod and if you have not coded taking prod environment in mind most likely code will fail in prod or result in exceptions.So what makes production environment different than development environment? Here are few things which I noted:

1) Production is all about load which will expose concurrency issues, load issues, memory and CPU issues.

2) You will get a lot many scenarios in production that you might have thought in development. If think through process is not applied than most likely those scenario has not handled in production.

3) Different data input or incorrect data, one of classic problems in production is the data which gets input to your program, be it from upstream system or any other place you will get all sort of data and if your program doesn't handle those very likely it will suffer.

4) Boundary conditions, this is some what related to above point data and scenarios but most of the boundary condition e.g. null, empty etc exposed in production.

So if a code is written all these things and potentially domain specific things and can sustain test of production than it called a production quality code and believe me it takes a lot of experience, skill and think through process to write production quality code not just in first time even after two or three iteration but as a developer we should always strive for writing production quality code in first attempt.

Now let's see how we can do that, what are the things we should keep in mind:

1) Get your requirements right, understand the problem , talk to user or business person as much as possible this will help you to find different scenario as early as possible. Many times business or user not tell you everything its not there fault but it doesn't come in mind right through. So if you are frequently speaking, discussing and presenting solution to them most likely they will ask questions, give feedback which eventually expose more scenario and subtle details. Here experience plays an important role. More experience or domain knowledge you, much better code you will write.

2) Think through, Think through and Think through. There is no substitute of this, it is more of a skill and art than science but you will get hold of this when you get more experience. For example if user says that you need replay capability in your program. You should be able to think of all possible scenarios where you need to replay and what could be required for that, what would be side effect of that. Does replay would be requested, what if the requesting system went down again, will you be able to re replay etc.

3) Boundary condition, always think that you will get bad input , you will get null or empty, small or very large numbers, function may get called at wrong time etc. you can get rid of this by writing unit test for each boundary condition.

4) Concurrency, this is is the major culprit and big problem which exposes itself in production when due to load multiple thread gets triggered and access your program concurrently. With high speed low latency electronic trading system and with many other java system where its requirement to have a concurrent application this can only be addressed by proper design , if you get the design right you will safe other wise you will need to bear the pain of redesigning or rewriting code. You can also expose concurrency issue by doing load testing in early QA cycles.

5) Exception handling, this is by far most important characteristic of production quality code, it must be able to handle exceptional scenario in clear cut predefined way. Whole program should never be crashed due to one single bad input or scenario.

6) Recoverable, code should be able to recover itself in case of premature closing or crash.

Though these are just some points which I am able to thought, there are lots more and it’s a constant process of improving yourself and I always strive for this. Please share how you guys write production quality code, what are things you guys keep in mind, what questions you guys ask to yourself and to user ?

Thank you.

Related Java Tutorials

Variable argument or Varargs methods from Java 5 with Example - Programming Tutorial

Variable argument or varargs in Java allows you to write more flexible methods which can accept as many argument as you need. variable arguments or varargs were added in Java 1.5 along with great language features like Java Enum, Generics, auto boxing and various others. Variable arguments a relatively small feature but useful for a developer who has been well aware about method and array. Some time we have a scenario that one method can take variable number of argument  and now with varargs from language makes it much easier. In this Java tutorial we will see How variable arguments makes it easy to write convenient method which can accept any number of arguments,  perfect candidates are sum() and average() kind of methods.

This article is in continuation of exploring features of Java programming language. I have already covered fork-join framework from Java 7 and automatic resource management or ARM blocks, if you haven't read them already you may find them useful.

Wednesday, September 21, 2011

10 examples of displaytag in JSP, Struts and Spring

Display tag is one of the best free open source library for showing data in tabular format in a J2EE application using jsp, struts or spring. it is shipped as tag library so you can just include this  in your jsp and add corresponding jar and there dependency in class-path and you are ready to use it. Display tag is my favorite solution for displaying any tabular data because of its inherent capability on paging and sorting. It provides great support for pagination by its own but it also allows you to implement your own pagination solution. On Sorting front you can sort your data based on any column, implement default sorting etc.

display tag examples in jspThere is so much resource available on using display tag including examples, demos and guides. In this article we will see some important points to note while using display tag in jsp. Though this library is very stable and rich in functionality still there are some subtle things which matters and if you don't know you could potentially waste hours to fix those things. These are the points I found out while I was using displaytag in my project and I have listed those down here for benefits of all.

displaytag examples
I have outlined all the examples based upon task I had to perform and due to those tasks I discovered and get myself familiar with displaytag. It’s my personal opinion that task based approach works better in terms of understanding something than feature based. It’s simply easy for mind to understand problem first and then solution.

1) Provide UID while using two tables in one page.
In many scenarios we need to show two separate tables in one jsp page. We can do this by using two tag easily but the catch is that sorting will not work as expected. When you sort one table, second table will automatically sort or vice-versa. To make two tables independent of each other for functionality like exporting and sorting you need to provide "uid" attribute to table tag as shown below. I accidentally found this when I encounter sorting issue on display tag.

<displaytag:table name="listofStocks" id="current_row" export="true" uid="1">
<displaytag:table name="listofStockExchanges" id="current_row" export="true" uid="2">

just make sure "uid" should be different for each table.

2) Displaytag paging request starts with "d-"
There was bug in one of our jsp which shows data using displatag, with each paging request it was reloading data which was making it slow. Then we thought to filter out displaytag paging request and upon looking the pattern of displaytag paging request we found that it always starts with "d-", so by using this information you can filter out display tags paging request. Since we were using spring it was even easier as shown in below


Map stockParamMap = WebUtils.getParametersStartingWith(request, "d-");
if(stockParamMap.size() !=0){
out.println("This request is displaytag pagination request");

3) Getting reference of current row in displaytag
Many times we require reference of current row while rendering display tag data into jsp page. In our case we need to get something from currentRow and then get Something from another Map whose key was value retrieved from current row, to implement this of course we some how need reference of current row in display tag. After looking online and we found that by using "id" attribute we can make current row reference available in pageScope. Name of variable would be the value of "id" attribute, this would be much clear by seeing below example:

<displaytag:table name="pennyStocks" id="current_penny_stock" export="true" uid="1">
<di:column title="Stock Price" value="${pennyStockPrice[current_penny_stock.RIC]}" sortable="true" />

This way we are displaying stock price from pennyStockPrice Map whose key was RIC(Reuters Information Code) of penny Stock. You see name of variable used to refer current row is "current_penny_stock"

4) Formatting date in displaytag in JSP
Formatting date and numbers are extremely easy in display tag, you just need to specify a "format" attribute with <displaytag:column> tag and value of this tag would be date format as we used in SimpleDateFormat in Java. In Below example I am showing date in "yyyy-MM-dd" format.

<di:column title="Stock Settlement Date" property="settlementDate" sortable="true" format="{0,date,yyyy-MM-dd}" />

You can also implement your own table decorator or column decorator but I found this option easy and ready to use.

5) Sorting Columns in display tag
Again very easy you just need to specify sortable="true" with <displaytag:column> tag and display tag will make that column sortable. Here is an example of sortable column in display tag.

<di:column title="Stock Price" property="stockPrice" sortable="true" />

6) Making a column link and passing its value as request parameter.
Some time we need to make a particular columns value as link may be to show another set of data related to that value. we can do this easily in display tags by using "href" attribute of <displaytag:column> tag, value of this attribute should be path to target url.If you want to pass value as request parameter you can do that by using another attribute called "paramId", which would become name of request parameter.

Here is example of making link and passing value as request parameter in displaytags.

<di:column property="stockSymbol"  sortable="true" href="details.jsp" paramId="symbol"/>

Values on this column will appear as link and when user click on the link it will append a request parameter "symbol" e.g symbol=Sony

7) Default sorting and ordering in displaytag
If you want that your table data is by default sorted based upon a particular column when displayed than you need to defaine a column name for default sorting and an order e.g. ascending or descending. You can achieve this by using attribute "defaultsort" and "defaultorder" of <displaytag:table> tag as shown in below example.

<displaytag:table name="pennyStocks" id="current_penny_stock" export="true" defaultsort="1" defaultorder="descending" uid="1">

This will display table which would be sorted on first column in descending order.

8) Sorting whole list data as compared to only page data in display tag
This was the issue we found once we done with our displaytag jsp. we found that whenever we sort the table by clicking on any sortable column header it only sort the data visible in that page, it was not sorting the whole list provided to display tag I mean data which was on other pages was left out. That was not the desirable action for us. Upon looking around we found that display tag by default sort only current page data but you can override this behavior by providing a file in classpath and including below line in
sort.amount = list

9) Configuring displaytag by using
This was important piece of information which we are not aware until we hit by above mentioned issue. Later we found that we can use to customize different behaviours, appearence of displaytag. Another good behavior we discoved was showing empty table if provided list is null or empty. You can achieve this by adding line "basic.empty.showtable = true". Here was how our properties file look like

sort.amount = list
basic.empty.showtable = true
basic.msg.empty_list=No results matched your criteria.

10) Specifying pagesize for paging in a JSP
You can specify how many rows you want to shwo in one page by using "pagesize" attribute of <displaytag:table>. We prefer to use it from configuraiton because this was subject to change.

Overall we found that displaytag was quite rich in functionality, easy to use and highly configurable. Displaytag is also very extensible in terms of customizing export or pagination functionality. has some very good examples and live demo addressing each of display tag functionality and those are excellent starting point as well. No matter whether you are using struts, spring or plain sevlet based framework for tabular data displaytag is a good choice.

Note: In <displaytag:table> displaytag is tag prefix I used in while declaring tag library using <@taglib> in JSP.

Related Java Tutorials

Tuesday, September 20, 2011

Difference between HashMap and HashSet in Java

HashMap vs HashSet is the most frequently asked question during any core java interview and interview is not said completed until they will not cover the Collection Framework and multi-threading interview and collections are uncompleted without Covering Hash Set and Hash Map.
Both HashMap and HashSet are part of collection framework which allows us to work with collection of objects. Collection Framework has their own interfaces and implementation classes. Basically collection is divided as Set Interface, List and Queue Interfaces. All this interfaces have their own property also apart from they get from collection like Set allows Collection of objects but forbids duplicate value, List allows duplicate along with indexing.Queue woks on FCFS algorithm.

First we have one look on What HashMap and Hashset is then will go for Differences between HashSet and HashMap

What is HashSet in Java?

HashMap vs HashSet, difference between HashMap and Hashset in JavaHashSet  is implementation of Set Interface which does not allow duplicate value all the methods which are in Collection Framework are also in Set Interface by default but when we are talking about Hash set the main thing is objects which are going to be stored in HashSet must override equals() and hashCode() method so that we can check for equality and no duplicate value are stored in our set.if we have created our own objects we need to implement hashCode() and equal() in such a manner that will be able to compare objects correctly when storing in a set so that duplicate objects are not stored,if we have not override this method objects will take default implementation of this method.

public boolean add(Object o)  Method is used to add element in a set which returns false if it’s a duplicate value in case of  HashSet otherwise returns true if added successfully.

What is HashMap?

HashMap is a implementation of Map Interface, which maps a key to value.Duplicate keys are not allowed in a map.Basically map Interface has two implementation classes HashMap and TreeMap the main difference is TreeMap maintains order of the objects but HashMap will not.HashMap allows null values and null keys.HashMap is not synchronized,but collection framework provide methods so that we can make them synchronized if multiple threads are going to access our hashmap and one thread is structurally change our map.

public Object put(Object Key,Object value) method is used to add element in map.

You can read more about HashMap in my article How HashMap works in Java and Difference between HashMap and hashtable in Java

Difference between HashSet and HashMap in Java

Following are some differences between HashMap and Hashset:

Hash Map
Hash Set
HashMap  is a implementation of Map interface
HashSet is an implementation of Set Interface
HashMap Stores data in form of  key value pair
HashSet Store only objects
Put method is used to add element in map
Add method is used to add element is Set
In hash map hashcode value is calculated using key object
Here member object is used for calculating hashcode value which can be same for two objects so equal () method is used to check for equality if it returns false that means two objects are different.
HashMap is faster than hashset because unique key is used to access object
HashSet is slower than Hashmap

Please let me know if you need any other difference between HashSet and HashMap in Java and I will add them here.

Related Java Tutorials

Saturday, September 17, 2011

Java 1.5 Generics Tutorial: How Generics in Java works with Example of Collections, Best practices, Gotchas

Java Generics Tutorial
Generics in Java is one of important feature added in Java 5 along with Enum, autoboxing and varargs , to provide compile time type-safety. Generics is also considered to be one of tough concept to understand in Java and somewhat it’s true as well. I have read many articles on generics in Java, some of them are quite good and detailed but I still felt that those are either too much technical or exhaustively detailed, so I thought to write a simple yet informative article on Java generics to give a head start to beginners without bothering there head too much. In this Java generics tutorial I will cover How Generics works in Java, Mysterious wild-cards in Generics and some important points about Generic in Java. I will try explaining generics concept in simple words and simple examples. On a different note, If you like to learn new concepts by following books then you should check Java Generics and Collection, one of the best book on Generics, which covers from basics to best practices.

By the way I thought about writing on Java Generics when I completed my post on Advanced Example of Enum in Java. Since Enum and Generics are introduced at same time in JDK 5. If you like to read about generics than you can also check my other tutorials on generics e.g. 10 generics interview question in Java and Difference between bounded and unbounded wildcards in Generics.

Friday, September 16, 2011

How to Convert Date to String in Java with Example

Some times we need to convert java.util.Date to string in java  may for displaying purpose I need it that while working on displaytag then I thought about this article  to list down various way of converting this in various ways, after some reading I found that SimpleDateFormat makes this quite easy. To get the feel of Date API in java and to familiarize ourselves with these classes we will see different examples of converting date to String in our application. Both DateFormat and SimpleDateFormat class belongs java.text package and they are very powerful and you can use them for conversion. it also good for parsing string into date and can be used to show in various locale also.

Difference between SendRedirect() and Forward() in JSP Servlet

Difference between SendRedirect and forward is one of classical interview questions asked during java web developer interview. This is not just applicable for servlet but also for JSP in which we can use forward action or call sendRedirect() method from scriptlet. Before examining difference on forward and SendRedirect let’s see what send Redirect method and forward method does.

SendRedirect ():  

This method is declared in HttpServletResponse Interface.

Signature: void sendRedirect(String url)

Thursday, September 15, 2011

How to use Fork Join in Java 1.7 - Tutorial with Example

What is fork Join framework in Java: Already popular project coin of JDK7 release has presented lot of good feature e.g automatic resource management, string in switch case, better exception handling in JDK7 etc. On of other important feature to note is fork join as name implies it divide one task into several small task as a new fork means child and join all the fork when all the sub-tasks complete. Fork/join tasks is “pure” in-memory algorithms in which no I/O operations come into is based on a work-stealing algorithm. Concept of fork join would be much clear by following diagram.

Wednesday, September 14, 2011

InvokeLater and InvokeAndWait in Java Swing (an example tutorial)

Everyone who is doing programming in java swing has to come across invokeAndWait and invokeLater provided by SwingUtilites. In this java swing tutorial we will learn about both invokeLater() and invokeAndwait() method. In first part we will mostly focus on invokeLater and will find answers of questions like What is invokeLater, how to use invokelater in java swing, example of invokelater in swing etc while in second part of this invokeLater tutorial we will learn more about invokeAndWait method in java swing and will learn Why we need InvokeAndWait, how to use InvokeAndWait method in java Swing and differences between invokelater and invokeAndWait.

Finally we will see code example of both invokeLater and invokeAndWait in Swing and will be able to decide when to use invokeLater and when to use invokeAndWait while doing Swing programming. 
We will also see famous Swing interview questions "difference between invokeLater and invokeAndWait" at end of article.


Why do we need InvokeLater method in Swing?

invokeAndWait invokeLater and SwingUtilities in javaBefore using invokelater or going deep about invokelater lets see why do we need this method in swingutility class? As we all know java swing is not threadsafe , you can not update swing component like JButton, JLable , JTable or JTree from any thread , they all needs to be updated from just one thread and we call it Event Dispatcher thread or EDT in short. Event Dispatcher thread is used to render graphics for java swing component and also process all events corresponding to key press, mouse click or any action. So if you want to update a particular swing component suppose label of a JButton from Yes to No you need to do this in Event Dispatcher thread and for doing this you need InvokeLater. invokeLater is used to perform any task asynchronously on AWT Event Dispatcher thread.

What is invokeLater in Java Swing

Invokelater is a method in java on swing package and belongs to swingutilities class. Invokelater is used by java swing developer to update or perform any task on Event dispatcher thread asynchronously.invokeLater has been added into Java API from swing extension and it’s belong to SwingUtilities class.

How does invokeLater works in Java Swing

If you see the signature of invokeLater method you will find that invokeLater takes a Runnable object and queues it to be processed by EventDispatcher thread. EDT thread will process this request only after sorting out all AWT pending events or requests. Even if invokeLater is called directly form Event dispatches thread processing of Runnable task still be done only after processing all pending AWT Events. An important point to note is that in case if run method of Runnable task throw any exception then AWT Event dispatcher thread will unwind and not the current thread.

Why do we need InvokeAndWait method in Swing

As we know that Swing is not thread-safe and we can not update the Swing component or GUI from any thread. If you try to update GUI form any thread you will get unexpected result or exception, it could be your GUI might not be visible or simply disappered. Only method which is thread-safe in swing is repaint() and revalidate(). On the other hand InvokeAndWait allows us to update the GUI from EDT thread synchronously. InvokeAndWait method also belongs to swingUtility class like invokeLater.

How does InvokeAndWait works in Java Swing

If you look at the signature of invokeAndWait method you will see that it takes a Runnable object and run method of that Runnable is executed synchronously on EDT. This is a blocking call and wait until all pending AWT events gets processed and run() method completes. Its a preferred way of updating GUI form application thread.

Important point to note is that it should not be called from EventDispatcher thread unlike invokeLater; it’s an error because it will result in guaranteed deadlock. because if you cal invokeAndWait from EDT thread it will be an AWT event and caller of invokeAndWait will wait for EDT thread to complete and EDT will wait caller thread to be completed so they will be locked in deadlock. Its also important to remember that if run() mehtod of Runnable object throw exception then its caught in AWT EDT thread and rethrown as InvocationTargetException on caller thread.

Example of InvokeLater in Java Swing

Here is an example of invokeLater() in Swing which will demonstrate that in case of invokeLater application thread doesn’t block.

Runnable pickHighBetaStock = new Runnable() {
public void run() {
System.out.println("High beta Stock picked by  " + Thread.currentThread());

System.out.println("This might well be displayed before the other message. if Event-dispatcher thread is busy");

Example of using InvokeAndWait in Java Swing

In this example of InvokeAndWait we will see that Application thread will block until Runnable object passed to EDT has been executed.

final Runnable pennyStockPicker = new Runnable() {
public void run() {
System.out.println("pick penny Stock on " + Thread.currentThread());

Thread stockPicker = new Thread() {
public void run() {
try {
catch (Exception e) {
System.out.println("This will finish after pennyStockPicker thread because InvokeAndWait is block call" + Thread.currentThread());

Difference on InvokeLater vs InvokeAndWait in Swing

Swingutilies provides us two methods for performing any task in Event dispatcher thread. Now let's see what the difference between invokeLater and InvokeAndWait is and when to use invokeLater.

1) InvokeLater is used to perform task asynchronously in AWT Event dispatcher thread while InvokeAndWait is used to perform task synchronously.

2) InvokeLater is non blocking call while InvokeAndWait will block until task is completed.

3) If run method of Runnable traget throws an Exception then in case of invokeLater EDT threads unwinds while in case of invokeAndWait exception is caught and rethrown as InvocationTargetException.

4) InvokeLater can be safely called from Event Dispatcher thread while if you call invokeAndWait from EDT thread you will get an error because as per java documentation of invokeAndWait it clearly says that "this request will be processed only after all pending events" and if you call this from EDT this will become one of pending event so its a deadlock because caller of InvokeAndWait is waing for completion of invokeAndWait while EDT is waiting for caller of InvokeAndWait.

5) InvokeLater is more flexible in terms of user interaction because it just adds the task in queue and allow user to interact with system while invokeAndWait is preffered way to update the GUI from application thread.

In Summary we can just say that since Swing is not thread-safe and we  cannot update different Swing GUI components on any thread other-than Event dispatcher Thread we need to use InvokeAndWait or InvokeLater to schedule any Runnable task for AWT Event dispatcher Thread. InvokeAndWait is synchronous and blocking call and wait until submitted Runnable completes while InvokeLater is asynchronous and non-blocking it will just submit task and exit."

That’s all on InvokeAndWait() and InvokeLater() method of SwingUtilities class. They are very important while doing GUI programming on Swing as well as this is very popular interview questions which I have discussed on my latest post on swing interview questions asked in Investment banks.

Please let me know your experience with InvokeLater() and InvokeAndWait() method and any issue you found while using them which would worth be mentioning here.

Some of my other tutorial in Java