What is SwingWorker

Swing is not thread safe as discussed with previous article. That means that any task which can take long time in execution should not be performed in Event Dispatcher Thread (EDT). Otherwise the EDT will be blocked and so the whole UI. So the solution, to perform the time intensive operations, is:

  • Start a new thread from EDT
  • Perform the heavy, time consuming task in this new thread
  • When task is done, update the Swing UI state or call any operation in EDT
  • EDT will invoke the operation

To perform above steps, we need to create a thread for time consuming task and also need to devise a mechanism to invoke the Swing Operation in EDT once the task is done (inter-thread communication). This involves some of the multi-threading code and may need to repeat it again and again with every such requirement. To abstract this code, and simplify this task; Java provides a SwingWorker class to hide all the complexities and hence the repeated work to perform these operations. It is an abstract class, which should be extended and some of its methods should be overridden to get the work done.

SwingWorker class has following important methods.

execute()
This method is the main method which should be called to start the work of SwingWorker class. As soon as you call this method, SwingWorker will give call to do the time consuming task in a new thread (described below).

doInBackground()
This method should be overridden by developer to do the time consuming task. This method will be called in a new thread, other than EDT, by SwingWorker. So any task performed on this thread won't affect the Swing UI operations. Once this method is done, result will be retained by SwingWorker which can be asked by using get() method. publish() method can also be called from this method to make the intermediate results available for GUI operations.

process()
It should be overridden if we want to process any data in EDT, as and when this data becomes available during doInBackground() operation. Suppose, one program is to load the heavy file from network which is being done in doInBackground method. Depending upon the data downloaded, you want to show the progress bar or some %age downloaded in a label on UI. This can be done by putting the work to update the label or progress bar in 'process' method. From 'doInBackground' method, we need to call the 'publish' method with the values which we want to publish; like %age data downloaded in this case. SwingWorker will call process method with this data in EDT. process method then can update the UI label. One more important point, SwingWorker may coalesced the multiple calls of publish in one call to process method, if previous calls were not executed till now. So if we are calling publish with suppose '%10', '%30', and then with '%50'; it might be possible that process method is called first with '10%' and then with '30%, 50%'. Process method should handle this case.

done()
This method is called by SwingWorker when task defined in 'doInBackground' method is finished. This is a place where final Swing UI updates should be done based on outcome from 'doInBackground' method. This method is called in EDT.

Object get()
This method is used to retrieve the result of task performed by 'doInBackground' method. Point to consider, that this method is a blocking method. So calling thread will be blocked till result is not available. So it must be used carefully, as if it is called from EDT, it will block the UI operations. One of the approach to use it could be to show model dialog box till result is received.

This way, SwingWorker class save us from defining the thread safe, and multi-threaded code again and again and work as a great utility class.

Why Swing is not Thread Safe

Big questions for Swing Developers - Why Swing is not Thread Safe? What makes Sun to design the Swing in a way that it can not handle its operation in multi-threaded environment? What if they made some extra efforts to make it thread safe, many developers would be relaxing now with comparatively simpler code? And so on..

So here is the answer. Swing is not made thread safe intentionally. It was a design decision by Swing team. Why? Because thread safety always comes at a cost. And access of Swing components in multiple threads may not be required that much.

What is thread safety and Why is that costly - Thread safety means that every part of the program should be safe to access from more than one thread concurrently. Program should be able to handle the concurrent access, either by serializing the access or ensuring that it is not disrupting the shared states or operations. Serializing the access means that access should be synchronized for access by thread, which will ensure that only one thread access the code block at a time after taking the necessary lock and hence guarantee the safe access to shared states. Or design has to be done in a way that program block does not affect any shared state or won't disrupt any operations due to concurrent access to states. Both of these changes are costly in term of performance or/and application design/development.

Why Multiple Thread Access may not be required - Because most of the UI operations are done in event fired by UI itself which are sequential in nature. There are few cases when we want to touch UI functions or states in parallel threads, like if we want to perform some time intensive operation to load the data and want to keep the UI active. But these cases are limited.

So if requirement to work in multi-threaded environment is very limited, and cost to make the code ready for multi-threaded environment is high; rationale is not to implement it. However, there should be provision using which developers can manage the UI operations in multiple threads environment also as mentioned above in case of loading heavy data in parallel.

This is what Swing Team analyzed and decided. Result is a high performing GUI development library for most of the scenarios with a capability to work with multiple threads also if required.

AWT vs Swing vs SWT

AWT, Swing and SWT are three main User Interface development technologies in Java. All three can be used to develop the desktop applications. Now the question is, which one to use and when? Each of these has its own pros and cons. In this article, we shall try to understand the pros and cons of each of these.

Let us start with AWT being the first Java GUI toolkit. It comes with standard Java packaging and hence no specific installations are required. This is the simplest form of GUI toolkit, where Java provide basic set of components, layout managers, events etc to design the desktop application.

AWT is dependent on host GUI controls (native peers). For every component in AWT, one equivalent host GUI control is built. This means, AWT directly utilizes the GUI control features set provided by host and is entirely dependent on this for available features. That is why it is called Heavyweight components library. As all the host does not support all the UI control, Sun decided to provide the least common denominator from all the UI controls available on different hosts. This means that AWT is having very limited set of controls and even lacks the generally required components nowadays like Tree, Table etc. If any application needs any of these components, it needs to be develop from scratch. That is a big task to develop the components which are quite commonly required in all kind of applications.

Various positive points of AWT are:
  • It is very stable toolkit
  • It is thread safe, which means it can work well in multi-threaded environment also. 
  • It disposes the controls automatically, so application need not to worry about it.
  • UI in AWT can be created in any sequence using bottom up or top down i..e we can start from parent to children or from children to parent; in any order actually. 

Create your own Hybrid Project Life Cycle

There are various project life cycle approaches in use for projects. All of these have their own pros and cons. So process should be picked after analyzing these pros and cons from project perspective. But it might be possible that none of the existing approaches are actually catering to all of your project or Organization requirements. Hence, it is also very much possible to mix more than one approaches, may be in different phases of project or in different activities. Many of the projects are executed with hybrid approaches. To understand this, let us first understand about most popular approaches in brief.

Waterfall Approach
It is one of the most used approaches for projects till now. It is in use since long. The approach suggests to plan for the whole project requirements in one go i.e.

  • Collect all requirements
  • Analyze and freeze the requirements
  • Do analysis and design for complete functions
  • Plan and Schedule the tasks for whole project
  • Complete the construction
  • Execute the testing of all functions
  • Fix the issues
  • Make the project live
  • Perform Maintenance activities
So you would see, it is a sequential approach to perform and complete all activities for a project going through conception, Initiation, Analysis, Design, Construction, Testing, Deployment to production and then Maintenance. Waterfall model comes from manufacturing and construction industries initially. Then it later adopted for software development also. And it actually worked well initially. It performs well for projects with comparatively stable requirements. 

Points in favor of this approach are that it give emphasis to complete the work for each phase with utmost perfection. It asks to design the system perfectly in design phase itself to avoid any restructuring later which can cost lot of money due to changes at large scale. It advocates to close the requirements in first phase itself, to avoid the changes later in project life. Due to these reasons, it results into a very stable project life cycle, easy to predict - plan - and budget. So it is good for budgeting also. It emphasize of documentation for each phase of project, and hence helps in creating the rich knowledge base. This remove the risk of loss of knowledge if any key member or members leave the project.

What is Pagination?

In many use cases, there is a generic requirement to show the list of data to user. User should be able to see the list of data, to perform search and sorting operations on this data. User should also be able to navigate to any data record anytime. This requirement demands to fetch the large amount of data from database and list it on UI for the user. Then this data can be filtered using various search criteria and can be sorted also depending upon user input. Approach to fetch the data can be different depending upon architecture and implementation of application, like data can be fetched directly from database in case of embedded applications, or 2 tier architecture or through some services in 3 tier architecture. The process flow used to be like:
  • Take inputs from user what kind of data she wants to see
  • Interact with database directly or through service (depending upon architecture) to get this data 
  • Display this data to user
  • Filter or sort the data depending upon user action on UI
For example, open google.com. Search for any word. You will get search results in list form, and various page number given at the bottom of the page to navigate to different pages. 

Now if there are thousands of data records in database for given inputs, all of this data can not be shown to user in one go. Showing this on same screen will be having problems like: 
  • It will not be a good experience for user, as she will need to scroll up and down a lot and information will be unreadable practically.
  • It will not be good for performance of application, as application may get out of memory or may face slow response due to large amount of data in memory, or data transfer from database.
To solve first problem mentioned above, we need to divide the data in small parts to show the user one part at a time. For example, we can divide data in parts having 50 records each. Then each of the parts can be shown to user one by one. Once user see first part, she can request for next or previous part and hence corresponding 50 records can again be shown on screen to user. These parts are called pages, and this process is called pagination - which divides the large data in pages (having limited records) and show these to user.

Vedic Math - Multiplication of any Numbers

Note: Vedic Math Blog has been moved to http://vedicmath.vedantatree.com/. Please bookmark the new address for new and existing blogs.

In the previous article, we have discussed few cases of Multiplication with "vertically and crosswise" sutra. In this article, we shall learn the remaining cases.

E. Multiplying three digit by three digit numbers
For example: abc x pqr



Multiply:
1) vertically                                              (a x p)
2) crosswise in both directions and add    (a x q) + (b x p)
3) crosswise in both directions and add    (a x r) + (b x q) + (c x p)
4) crosswise in both directions and add    (b x r) + (c x q)
5) vertically                                              (c x r)

Step2 and Step4 are same as we did in the previous sections i.e. multiplying crosswise with two columns at a time. But in Step3, we multiply crosswise using the outer columns, then multiply vertically in the middle column and add these numbers.

Vedic Math - Multiplication of any numbers

Note: Vedic Math Blog has been moved to http://vedicmath.vedantatree.com/. Please bookmark the new address for new and existing blogs.

In this article, we shall discuss the Vedic Math sutra "vertically and crosswise". This is the General Formula which is applicable to all the cases of multiplication. You will found this method very useful in division also that we shall discuss later. In the previous sutras, you subtracted crosswise; now you will multiply crosswise.

A. Multiplication of two digit numbers
For ab x uv


The numbers are written from left to right.
Now multiply:
1) vertically                                              (a x u)
2) crosswise in both directions and add    (a x v) + (b x u)
3) vertically                                              (b x v)

The answer has the form:   au | av + bu | bv

Following is the example of two-digit multiplication will make this clear:
12 x 23
 1         2
 2         3
--------------
2 | 3 + 4 | 6
= 2 | 7 | 6
= 276

The previous examples involved no carry figures, so let us consider this case in the next example.
64 x 93
 6          4
 9          3
-----------------
54 | 18 + 36 | 12
=54 | 54 | 12
=54 | (54 + 1) | 2         (Carry over the 1)
=54 | 55 | 2
=(54 + 5) | 5 | 2          (Carry over the 5)
=59 | 5 | 2
64 x 93 =5952

The Algebraic Explaination is:
Let the two 2 digit numbers be (ax+b) and (ux+v). Note that x = 10. Now consider the product
(ax + b) (ux + v)
= au. x2 + avx + bux + b.v
= au. x2 + (av + bu)x + b.v
The first term i. e. the coefficient of  x2 is got by vertical multiplication of a and u
The middle term i. e. the coefficient of x is obtained by the cross-wise multiplication of a and v and of b and u and the addition of the two products
The independent term is arrived at by vertical multiplication of 'b' and 'v'

More about Singleton Design Pattern

In our previous article about Singleton Design Pattern, we have discussed about basics of its working and design. Today we are adding more points to it.

While implementing singleton, we need to take care that it should work well in multiple thread environment. So one option is to initialize the instance eagerly at the time of declaring the variable. But if we want to initialize the variable lazily, i.e. only when it is required, then we can make the method 'getSharedInstance' synchronized. But that will slow down the operations in every request. But we need synchronization only if instance is null and we need to create it.

So one approach could be to use double 'null' check as given below:

getSharedInstance()
{
// first check to make sure that synchronization comes in effect only if instance is null
 if (instance == null )
 {
  // synchronizing to avoid access my multiple threads
  synchronized (this)
  {
   // check again if instance is not null, as first check of not null may be passed by more than one thread
   if (instance == null)
   {
    instance = new Instance();
   }
  }
 }
 return instance;
}

But in above approach, we are still synchronizing a code block, and checking the instance for 'null' twice. There can be another better approach as given below: 

public class SingletonObject 
{
  public static SingletonObject getSharedInstance ()
 {
   return SingletonHolder.sharedInstance;
 }

 private static class SingletonHolder 
{
 static SingletonObject sharedInstance = new SingletonObject();
}
}

Here no synchronization is required in code. The instance will be initialized lazily only when request will hit getSharedInstance method for the first time, as inner static class will be initialized then.

With these approaches, you need to take care of few points like
  • Cloning should not be supported
  • Constructor of class should be private
  • Serialization should be controlled, i.e. we should override readResolve method to return the shared instance.

But later 'Joshua Bloch' has proposed another approach, termed as best approach for implementing Singleton Patter. This is to use 'enum' for implementation. Example is given below:

// Enum Singleton
public enum SingletonObject
{
  SHAREDINSTANCE;

  public void someMethod()
  {
    .....
  }
}

And it is done. Now you can use it like

SingletonObject.SHAREDINSTANCE.someMethod()

It is perfectly thread safe without any double check for null or synchronization. Check in serialization methods are also not required, because Enum are serialization specially in Java by just writing their names in stream.

With this approach, there is no chance to have more than one instance of object with any of the hook. From Joshua book - 
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

Solution for 'NullPointerException' on Eclipse Startup

We faced a scenario where we abruptly had to kill the java while eclipse was running on system. However, when we tried to run the Eclipse again, it just get hanged and console/logs exposed us following error:

[weblogic@localhost oepe-indigo-12.1.1.0.1]$ /home/weblogic/Programs/Oracle/oepe-indigo-12.1.1.0.1/eclipse -vm /usr/java/jdk1.6.0_33/bin
LogFilter.isLoggable threw a non-fatal unchecked exception as follows:
java.lang.NullPointerException
at org.eclipse.core.internal.runtime.Log.isLoggable(Log.java:101)
org.eclipse.equinox.log.internal.ExtendedLogReaderServiceFactory.safeIsLoggable(ExtendedLogReaderServiceFactory.java:59)
org.eclipse.equinox.log.internal.ExtendedLogReaderServiceFactory.logPrivileged(ExtendedLogReaderServiceFactory.java:164)
org.eclipse.equinox.log.internal.ExtendedLogReaderServiceFactory.log(ExtendedLogReaderServiceFactory.java:150)
org.eclipse.equinox.log.internal.ExtendedLogServiceFactory.log(ExtendedLogServiceFactory.java:65)
org.eclipse.equinox.log.internal.ExtendedLogServiceImpl.log(ExtendedLogServiceImpl.java:87)
org.eclipse.equinox.log.internal.LoggerImpl.log(LoggerImpl.java:54)
org.eclipse.core.internal.runtime.Log.log(Log.java:60)
org.tigris.subversion.clientadapter.javahl.Activator.isAvailable(Activator.java:92)
org.tigris.subversion.clientadapter.Activator.getClientAdapter(Activator.java:67)
org.tigris.subversion.subclipse.core.SVNClientManager.getAdapter(SVNClientManager.java:127)
org.tigris.subversion.subclipse.core.SVNClientManager.getSVNClient(SVNClientManager.java:94)
org.tigris.subversion.subclipse.core.SVNProviderPlugin.getSVNClient(SVNProviderPlugin.java:462)
org.tigris.subversion.subclipse.core.status.RecursiveStatusUpdateStrategy.statusesToUpdate(RecursiveStatusUpdateStrategy.java:62)
org.tigris.subversion.subclipse.core.status.StatusCacheManager.refreshStatus(StatusCacheManager.java:270)
org.tigris.subversion.subclipse.core.resourcesListeners.FileModificationManager.refreshStatus(FileModificationManager.java:220)
org.tigris.subversion.subclipse.core.resourcesListeners.FileModificationManager.resourceChanged(FileModificationManager.java:161)
org.eclipse.core.internal.events.NotificationManager$1.run(NotificationManager.java:291)
org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
org.eclipse.core.internal.events.NotificationManager.notify(NotificationManager.java:285)
org.eclipse.core.internal.events.NotificationManager.broadcastChanges(NotificationManager.java:149)
org.eclipse.core.internal.resources.Workspace.broadcastPostChange(Workspace.java:395)
org.eclipse.core.internal.resources.Workspace.endOperation(Workspace.java:1530)
org.eclipse.core.internal.resources.InternalWorkspaceJob.run(InternalWorkspaceJob.java:45)
org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)

And the solution we found was, it happens because some of the metadata file got corrupted during abrupt exit. So we follows the steps mentioned below to get eclipse started again:
  1. cd .metadata/.plugins
  2. mv org.eclipse.core.resources org.eclipse.core.resources.bak
  3. Start eclipse
  4. It will start but will show errors with opened tabs. This is because we have changed the resources folder, which eclipse use for managing the resources
  5. Close all opened tabs
  6. Exit from Eclipse
  7. Delete any newly create org.eclipse.core.resources folder
  8. Rename back the 'org.eclipse.core.resources.bak' to 'org.eclipse.core.resources'
  9. Start Eclipse
  10. It should start fine with all projects
 Hopefully you won't face any problem further, but will depend on scenario. Please share your experience if that was different.

Vedic Math - Squaring numbers near base

Note: Vedic Math Blog has been moved to http://vedicmath.vedantatree.com/. Please bookmark the new address for new and existing blogs.

In the previous article, we have discussed about the method of multiplication by using the base value. In this article, we shall learn the squaring of numbers by using base value. Squaring numbers near base is much easier as there is no possibility of different cases that we discussed earlier for multiplication, like
1. One number is above the base and the other number is below it
2. Numbers near different bases like multiplier is near to different base and multiplicand is near to different base.

So it is comparatively simpler. Here, we can use the sub sutra “whatever the extent of its deficiency, lessen it still further to that extent; and also set up the square of that deficiency”.

In this, first corollary is “All from 9 and the last from 10”. This method will work for any type of squaring. There is another method by taking the sutra "Vertically and Crosswise" but that we will discuss later.

Suppose we have to find the square of 8. The following will be the steps for it:
1. We shall take the nearest power of 10 (10 itself in this case) as our base.
2. 8 is '2' lesser than 10, so we shall decrease 2 from 8 (i.e. 8 - 2 = 6). This will become the left side of answer.
3. And, for right part of answer, we write down the square of that deficiency i.e. 2 x 2 = 4
4. Thus 8 x 8 = 64

In exactly the same manner, we say
72 = (7-3)  |  32
     =  4  |  9
     =  49

92 = (9-1)  |  12
     =  8  |  1
     =  81

62 = (6-4)  |  42
     =  2     |     6                (Here, since right side is 2 digit number, so '1' will be carried to its left)
                   1
     =  3     |   6        
     =  36