Khangharoth

May 16, 2007

Java Collection :When to Use Which

Filed under: Java — khangharoth @ 3:26 am

This is a presentation made by Divya and Devendra in fresher training at Eigen under me ,Our main aim in this presentation was to dig on Java Collection framework.

One of the thing that i found missing on almost all tutorials on net and in available book’s is some simple strategy to make a choice about which Data-Type to use.What i have seen is most of us only read about all these but in projects we just use one or two data structure say ArrayList ,even if we are adding and deleting the list often than search functionality.

I was just going through this and thought that it will be good idea if other can also view and give their inputs.The idea is to make this template some sort of guideline for choosing a particular data structure in Java.

collection1.png

This is basic flow diagram,go through the ppt and do comment on how to make it more Useful.

Note:Vector are missing in this ppt , should have been part of it.

Collection.ppt

May 15, 2007

Encryption of Password in Java

Filed under: Java — khangharoth @ 4:31 am

If you are developing a web application and managing User session on the basis of User password.With the traditional way of storing of storing user password as it is in a Db table is not very elegant.Anybody who has the access to Db can get those passwords .This problem is more acute than it seems as most of the Users keep same Login-Id and Password.

So in era of Outsourcing and remotely managed servers and with traditional method of storing password you can never be sure who all are peeking into the User information.

One very simple solution can be to encrypt or in technical terms  to generate a Hash-Key corresponding to the User entered Password and store this i database.When User login again,than take the entered value ,convert into Hash-Key and compare it with value in Db for authentication.

This is very simple yet powerful way,if your application demands more security than you must probably look Jasypt  .

PasswordService.txt

May 12, 2007

MultiThreading Programming In Java.

Filed under: Java — khangharoth @ 9:57 am

Let’s first understand Concurrency :Concurrency is a property of Systems in which several computational process are executing at the same time and potentially interacting with each other.

Concurrency may be physical ,if each unit is executed on a dedicated processor.Its also called true concurrency. If your system has only one CPU ,than it can’t perform true concurrency.Now we have multiple CPU’s in mainstream systems,and these systems are capable of Parallelism or true concurrency.

Concurrency can be logical,If you have single processor system than this is what your system does.Concurrency is just a illusion created by CPU.CPU can execute only one of the programs at a time. The OS maintains the illusion of concurrency by rapidly switching between running programs at a fixed interval, called a time slice. The time slice has to be small enough that the user doesn’t notice any degradation in the usability and performance of the running programs, and it has to be large enough that each program has a sufficient amount of CPU time in which to get useful work done.

So with these basics now let’s move towards more concrete.

Processes (Program) & Threads

  • Process: Is a self contained running program with its own address space.Typically two process share very minimal data,not more than filename etc.Or we can say sharing of data variable is not their.Typical processes on your system are Window Media Player,Outlook,Eclipse etc.These are processes which have their separate memory area and sharing is minimal between them.
  • Operating System is capable of switching the CPU from one process to another ,giving a feel that Media Player and eclipse are running simultaneously.If you are still not clear that perhaps TV analogy will help.In TV ,static images are refreshed on screen so fast that to human mind it appears continuous.
  • Thread or we can say Light-Weight process are concurrent Units which share a single address space.So sharing of data is very common and high.

I think now the difference between a Thread and a Process is clear.Just to make it more clearer:

  • Threads are lightweight compared to processes.
  • Code and Data sharing is easily done in threads as they share same address space.
  • To put in proper perspective , A process can be single threaded or multi threaded.

Its the O.S which switches between various processes and various threads in a single process.Their are different models to achieve this

  • Preemptive multitasking. In preemptive multitasking, the operating system decides how to allocate CPU time slices to each program. At the end of a time slice, the currently active program is forced to yield control to the operating system, whether it wants to or not. Examples of operating systems that support preemptive multitasking are Unix, Windows 95/98, Windows NT and Mac OS X.
  • Cooperative multitasking. In cooperative multitasking, each program controls how much CPU time it needs. This means that a program must cooperate in yielding control to other programs, or else it will hog the CPU. Examples of operating systems that support cooperative multitasking are Windows 3.1 and Mac OS 8.5

Modern O.S generally use preemptive model so your running thread can loose control at any point of time even in some simple assignment statements which seems atomic.Its a very important concept to be learned that a thread can loose control at any stage and will start from that point when again its turn will come.Their are some guaranteed atomic operations in java .

We want to start a new thread when we have a piece of code which can run independently .If done correctly it results in better user experience and also increased performance. To better understand need of multi threading in normal programming lets take an very common example.

Example:Suppose we have a Swing Gui and its displaying a list of Employee’s name and in front of each name their is a button “Get Details”.On click of a specific button ,application picks the corresponding name and retrieves all data related to that employee for display. On Click of button ,action perform method will be called and from this we can make a database call ,gets all the data and than populate the Gui.The catch here is ,action perform method is called by Swing Event Thread.And if we make database call from this thread itself ,till the time our work is complete ,it won’t be able to perform its other responsibility like painting/repainting and firing events.Now if the application task takes too much time (500ms) ,the Gui would appear hang and unresponsive.

This is the perfect place to do Application work in separate thread and free the Event thread as early as possible.So the flow should be: Event Thread(Gives the trigger :Name) —-initiates and returns–>Worker Thread (gets the data related to name ) —hand over data to Event thread–>Swing Thread(updates the Gui).

So Swing thread is free to perform its own responsibilities in the mean time a Time-Consuming task is been performed.I suppose now its clear why multi threading capabilities are needed in modern applications.Sometimes designing a complex problem is easier in concurrent threads rather than in a single flow,like user events with some other task also running.

Now its time to take some real Java examples.In java their are two ways to start a thread.

  • Create a Class which extends Thread Class :Than you put you application code in overridden run method.Basically anything we want to do from this thread is put in run method.Try out example in SimpleThread.txt.Here its important to note that order of execution does not depend on which thread was started first,try for 10-15 times you will notice that sometimes its the second thread which started first although we have done in other way round.So its important to note that we cannot guarantee about the order of execution and also the behavior can be different on different O.S.
  • Create a Class which implements Runnable Interface : In this case also we would put our code in run method.And to start anew thread,we will create a new thread and pass runnable instance to it.Try out example in RunnableExample.txt.Here also order is not guaranteed.

So which is the more preferred way.Well most of the time its the second which is used,because generally our classes are already of some type say Swing Component has so have to extend some other class.In java as multiple inheritance is not allowed so we give thread properties to a class by implementing runnable.

Their is one more handy way to use in application.In our example we just wanted to do some work in a separate thread.To achieve that we can directly use

Thread thread=new Thread(new Runnable(){

public void run() {
/*
* Put your work related code here
*/

}});
thread.start();

Now let’s go through the Life Cycle of a thread for better understanding : A thread can be in one of four states during its lifetime.

  • new – A new thread is one that has been created (using the new operator), but has not yet been started.
  • runnable – A thread becomes runnable once its start() method has been invoked. This means that the code in the run() method can execute whenever the thread receives CPU time from the operating system.
  • blocked – A thread can become blocked if one of the following events occurs:
    • The thread’s sleep() method is invoked. In this case, the thread remains blocked until the specified number of milliseconds elapses.
    • The thread calls the wait() method of an object. In this case, the thread remains blocked until either the object’s notify() method or its notifyAll() method is called from another thread. The calls to wait(), notify() and notifyAll() are typically found within synchronized methods of the object.
    • The thread has blocked on an input/output operation. In this case, the thread remains blocked until the i/o operation has completed.
  • dead – A thread typically dies when the run() method has finished executing.

Also stay away from these methods of Thread Class :stop(), suspend() and resume() .Usesage of these can result of unpredictable results in your program.These methods have been deprecated by Java team.

SimpleThread.txt
RunnableExample.txt

May 11, 2007

Antialiased Printing from Java : Solution

Filed under: Java — khangharoth @ 2:20 pm

In continuation to the last post ,I would like to share what i understood till now.

With Java if you do component printing that is you right code in print method of Component implementing Printable interface,with the help of commands like

g2.drawLine(x1, y1, x2, y2);

g2.drawRect(x, y, width, height);

than you will get anti aliased printing  .That is no jagged effect,a very smooth print.But if you will give print of a Raster data say PNG or JPEG image ,in this case you will use something like

g2d.drawImage(image, 0, 0, width, heigth, this);

than chances are that you will get jagged print .

The difference in both these are  :1) In first case you are telling that you want to draw a line and you provide two points.Your java call is taken up by OS specific printerJob,on windows it will be Win32PrinterJob.Now this printerJob interacts with the driver of the printer to convert into a specific printer understandable vector format.

In host machine,printer driver is the interface between the printer and your application. So to print your application should be able to locate the plotter driver and dump all the data either from GDI buffer or Opengl buffer for printing.

So the crux is ,you just give instruction about how to draw in Java2D and it will be passed on to GDI libraries of Windows platform and than from printer Driver interface to printer.So all the work of maintaining quality is done by Windows.

More on Java printing will come in subsequent blogs!

May 10, 2007

HPGL Output from Java : Vector Printing ,Not Raster

Filed under: Java — khangharoth @ 2:37 pm

Currently i am working to implement a Plotter functionality in our Java based CAD Application.

If we use normal printing ways or more precisely Raster printing ,life is very easy.It can be summed up as

  • Create a Raster Buffer .We can do this by say capturing a screen shot and prepares a Buffered Image.
  • Set up Java printing interface.
  • Send this Raster data to printer.

It’s ok for normal requirements but for Industrial applications like CAD industry you don’t want jagged effects in say line which has been printed.

For high quality smooth printing we have to send data in Vector form to the Printer.

The difference in Vector and Raster data is  ,in Vector to draw a Circle we send something like Circle,center,Radius information to a printer.But in Raster we send all the points or pixel buffer to printer,printer doesn’t know that it is a circle .Its just draws the pixel buffer.

Ways to send Raster Data :GIF,JPEG,PNG.

Ways to send Vector Data :PLT,PostScript.

Now i am trying to do it by PLT format.The problem i am facing is PLT depends on type of printer and so i have to get driver properties and convert neutral .plt file to printer specific .plt file.But by Java i am not been able to get Driver properties.

Still trying to figure a way out !

Note:I am still in R&D phase so i may be wrong in what i have said above.

May 7, 2007

Check,Debug your Swing App

Filed under: Java — khangharoth @ 11:54 am

If you are building a desktop application and using Java as programming platform ,than you must already be aware of these problems.If you are facing problems like GUI freezing or dead look in Swing event dispatch thread and this results in arbitrary painting/repainting problems.

Firstly their should be no mixing of AWT/Swing components.Now Swing has evolved a lot and so their should be no excuse to use AWT components,Only if you are making a Graphics application and using things like JOGL ,GLCanvas than it makes sense to still use AWT GLCanvas rather than Swing GLJPanel.

Before problems,lets just quickly sums up responsibilities of Swing Thread.

i) Painting/Repainting of the Java Components.

ii) Fire Events.

iii) Your App work,if you have placed your application logic in some action-perform method.This is one area you should be careful,if it takes time to execute (even 100ms) your Gui will start behaving unresponsive.You can use things like SwingWorker ,SpinOff,Foxtrot etc.

If mixing of AWT/Swing is not the problem and still your Gui is giving you some problems.Let’s try to list down some common problems in a Swing based Gui.

1) Gui just hangs and if you do any operation like resize etc,everything is just gone.Even if you wait for some some time ,it never comes to life.This means some deadlock has occurred to the Swing thread.

a) Check if you are taking any Lock in Swing Event thread.This is one of the most common mistake.

b)If you are doing some I/O or network operation from some action-perform method.

c) Also i have seen some junior programmers directly write data-base interaction code in action-perform method.This strategy can give you problems like ,running fine on our environment but on Client everything just hangs.

2) Gui hangs momentarily and then repaints itself.This is easy to debug as you are doing some time-consuming task in Swing thread and so its painting mechanism has suffered.

As Swing is not designed for Fail First approach ,most of the problems remain buried under when you have small Gui.The moment your Gui code becomes appreciable ,all these problems start popping out at unexpected times.

So the best strategy is to make your Swing development as Fail-First . Well this means the moment you have done something which violates the best practices,your program should fail rather than cover up this small problem.

You can use these two Classes to constantly monitor health of your Swing Gui.

  • EventDispatchThreadHangMonitor.java
  • CheckThreadViolationRepaintManager.java

I found these utilities on net and using them has helped me a lot.

How to use them? —-> Include this is your package Structure and Just insert these two line in your start of the application.

EventDispatchThreadHangMonitor.initMonitoring();
RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager());

Swing has really came a long way!

May 6, 2007

Failure Of a Software Project

Filed under: Software Design — khangharoth @ 5:40 pm

Last night i was having a chat with one of my former college and he was telling me about his project being scraped and how this has resulted in undue pressure on them and effecting moral of the entire team.

What really amaze me is that how often i hear these stories,and is their any other industry with failure rate as high as Software.

I did some googling to come up with some solid numbers and was totally aback to see overall software failure rate is around 63%.Here the guideline is that any software which has not covered its investment cost will be considered as failure.What is more astonishing is around 46% of software are never completed or delivered to client.

Now what makes Software field so different from other processes like Manufacturing or say Construction.These disciplines have really shown a commendable success with even very complex set of problems.Here i would like to quote from one of my favorite blog Coding Horror.
I don’t think bridge building has anything in common with software development.* It’s a specious comparison.
Software development is only like bridge building if you’re building a bridge on the planet Jupiter,
out of newly invented materials, using construction equipment that didn’t exist five years ago.

I can understand the frustration of any Software developer when our process is compared with other Industries and people start uttering words like assembly-line,automation,Six-Sigma etc.I really like assembly-line comparison because its really funny.Let me explain you:

           The argument is that Industries like automobile have perfected the art of making automobiles to such an extent that a new Car is roll out in less than 3 minutes from a assembly line.

                                                       Now my response is the time we are talking about here is time taken to make a duplicate copy.In automobile industry also to churn a new model still takes more than a year.Now if apply this logic than how much time we take in making a copy of a developed software.It took Microsoft around 5 years to comes with Vista but how much time will they take to come up with say 1 billion copies of Vista,sorry folks this is not the way you can compare things.

But still question ,why Software projects fails so much is very important,as their is lot of money involved with it.You can read some research finding here to get some feel about this question Failure Rate.I’ll just highlight some important findings:

  • An IT project is more likely to fail than succeed.
  • 20% projects can be termed as successful.
  • The larger the project the more likely is the Failure.

And i would like to add my favorite “The More MBA’s are in a project,the more likely is the failure” ,that’s why companies like Google don’t hire MBA’s but promote internal technical people to manage Projects.

My list of reason’s about this:

  • Lack of Career path for technical people.At some point of time they have to move to managerial level to advance their careers.Companies like Google and Microsoft are noticeable exception to this.
  • Specially in Indian Context:A person with 5 years of experience rarely codes.So coding is always done by freshers ,who are learning about How To Code.No matter how good is the design if the people who are actually writing the code are not experienced than we know what to expect from code!
  • Mad rush for Cost Saving and buzz word like Out-Sourcing and off-shoring.A software projects has two type of costs ,Real or upfront cost and hidden or maintenance cost.One should include both the costs and not just see that in location X we can hire developer for pennies.
  • Unrealistic Time lines:Every Software when developed is happening for the first time so add uncertainty factor in your time lines.The more same kind of projects you will take ,the less will be the uncertainty factor.

What i think about how to improve this situation:

  • Stringent hiring process.Don’t recruit in masses.One common argument is that we are not able to find good people.If their aren’t good people available than its not the place to be in.
  • Very high emphasis on learning and constant improvement.In-fact the ideal work to learning ratio can be 75:25.This means out of office time ,employees spend 75% of time on active work and around 25% time in improving their skill set.
  • If you have Out-Sourced your project to a vendor than each quarter randomly select some developers from vendor’s developer  list and taking technical test .This will keep your vendor on toes.
  • In software resource planning 1+1 !=2 ,its simply not equal you have to add communication cost and hence bigger the team more is the communication cost in terms of time.
  • 3 average programmers are not better than 1 good programmer .Programming is not a physical task so why compare in physical terms.

what you think?What could be more reason’s and remedies for this problem.I am as much interested to know as you are!

May 4, 2007

JavaScript :No relation with Java

Filed under: Java — khangharoth @ 11:41 am

JavaScript is indeed is quite a mystery and what really baffles is everybody uses
it but nobody understands it.

The reason behind this is we just use JavaScript as filler language or as a toy language.
We don’t do any serious business logic into this,but some form validation or for some
arbitrary GUI requests like enabling and disabling of buttons on form load etc.
Debugging in JavaScript is also a big task and makes the language more obscure.

If you are an Web-Application developer working on a Java platform(i have very little idea
about Microsoft World:It just seems different and Closed,No open-Source!).Than you will
most of the time choose either ‘Struts-JSP’ or ‘Web-Work-Velocity’ approach.Words like MVC and
Separation of Layers are at center stage ,in mid of all this if you have a small requirement
like some X button should be disabled till the time some internal-Frame gets Loaded,than its
the JavaScript which will help you.

But the moment your Jsp has noticeable amount of JavaScript ,you can see the frown on the face of
your Senior.’
I came across a video-presentation from ‘Yahoo! JavaScript Architect Douglas Crockford’ and its
quite interesting especially when you get to know about history and than things look more
in order.General questions like why JavaScript has name Java associated with it,is it some strip
down version of Java will get answered in this.

Its a good introduction about JavaScript.Here’s the link to Video 🙂

The JavaScript Programming Language

May 2, 2007

Enterprise System Architecture

Filed under: Software Design — khangharoth @ 2:09 pm

Their is very important debate doing rounds on net as what actually an Java Architect (Enterprise Systems) do ?Isn’t Architecture is broader term and should be used independent of Language and so term Java Architect is misleading.

Well what i think is its very difficult to find a person who has no bias of platform and language and this bias comes not because of personnel linking but the person will have more knowledge or have worked on a particular platform more and hence in new coming projects he is likely to choose already tried and used technology .And this loop ends up labeling a person as Java Architect or .net one.

One more interesting point is made at blog Architecture? One size fits all

In this author had boldly proposed a single solution to cater around 99% of Enterprise systems.I am enclosing his diagram and on first look it looks like most of the Systems have same Architecture.

In this also from 10,000 ft everything looks same but real challenge is figuring out technology from plethora of choices .Problem of plenty is valid especially in Java.What was supposed to be strength of Java has becomes its Achilles heel.

Its time when big guns like Sun,IBM,BEA ,Google sit together and standardize common choices.

But than it is the completion and open-source which will determine shell-life of any new technology.

Create a free website or blog at WordPress.com.