Showing posts with label Tricks. Show all posts
Showing posts with label Tricks. Show all posts

Sunday, 29 September 2013

Premature optimization is an root of all evil

This post is for them who is obsessed with performance of there Java application

most people complaint that Java is slow, but after years of experience in Java i can say that Java itself is not slow, poorly written applications are slow. 

Things you should do when you code any application in Java

Java is mostly used as a Server side technology, but if you are making a Desktop application or providing a client application for you web application then you must consider the following suggestions

1. Always run you Swing GUI on EDT(Event Dispatching Thread) and perform your heavy task such as copying a long file or loading a heavy file in a editor using SwingWorker.

WHY SO ?

If you fully understand the Swing Rendering then you should not ask this question

In case if you don't then 
painting of Swing components must happen on the EDT. By calling synchronous paint methods, your code is implying that it is on the correct thread so that the right things will happen at the right time. If the calling code is not on that correct thread, the results could be undefined.


2. prefer Task & ExecutorService over Threads

ExecutorService manage Threads on your behalf it has capabilities to restrict number of threads to be ever created For e.g: if you have a production Server which is heavily loaded all times then this method will help you much because it will only create Threads you mentions which will provide room for others to run there own task and life will be more easier ....

Explaining every thing about concurrency framework is beyond the scope of this post

3. Prefer for each loop over traditional for loop
Although many compilers perform loop fusion techniques to improve performance of for loop it is also necessary to minimize the scope of variable using this technique

// No longer the preferred idiom to iterate
//over an array!
for (int i = 0; i < a.length; i++) {
doSomething(a[i]);
}


These idioms are better than while loops, but they aren’t perfect. The
iterator and the index variables are both just clutter. Furthermore, they represent
opportunities for error. The iterator and the index variable occur three times in
each loop, which gives you two chances to get them wrong. If you do, there is no
guarantee that the compiler will catch the problem.
The for-each loop, introduced in release 1.5, gets rid of the clutter and the
opportunity for error by hiding the iterator or index variable completely. The
resulting idiom applies equally to collections and arrays:


// The preferred idiom for iterating over 
//collections and arrays
for (Element e : elements) {
doSomething(e);
}


When you see the colon (:), read it as “in.” Thus, the loop above reads as “for
each element e in elements.” Note that there is no performance penalty for using
the for-each loop, even for arrays. In fact, it may offer a slight performance advantage
over an ordinary for loop in some circumstances, as it computes the limit of
the array index only once.

There are more things but i m running out of time ....!! Ta Ta...

Tuesday, 28 August 2012

Top 10 Tricks To Fool Your Java Professor

Trick #2

This week's trick will teach you how to find loopholes in existing programs for this you need to have deep understanding about how the underlying code works and how the Platform on which the code is running works.

Let me explain you this with an help of an example:-

Let us consider the simple and very basic example, our challenge is to write code which will tell us whether the given number is odd or not, so lets give a name to this program
ODD OR NOT
when given this challenge most people write this code:

If one can catch the flaw in this code then h/she is a Java Expert


public class OddOrNot
{
 static boolean isOdd(int no){
  return (no % 2) == 1;
 }
 public static void main(String[] arge){
  System.out.println(isOdd(7));
 }
}

Sadly if you are not the one, then i suggest you to read further


There are 2 flaw's in this code 
  1. Performance penalty (Mod operations are always less preferable)
  2. Code fails as soon as you pass a negative odd number 
Now you know the flaw, then you should be keen to know what best solution can be written for this type of challenges, stay connected....


why code fails ?
This is because, the java's truncating integer division operator[JLS 15.17.2], it implies that when the remainder operation returns a non zero result, it has the same sign as its left operand.  

So now you know the hidden flaw of the above written code, yes it return -1 as soon as you enter any negative odd number.

So, What is the best way to solve this challenge?
USE Bit-Wise-And (&), If you can use bit-wise-and (&) instead of mod (%) operation then always prefer bit-wise-and (&) operation, to increase performance of your application.

public class OddOrNot
{
  static boolean isOdd( int no ){
   return ( no & 1 ) == 1;
  }
  public static void main( String[] arge ){
   System.out.println( isOdd( -7 ) );
  }
}

Working
 If you convert any odd decimal number to its binary equivalent than you will get answer as pattern xxx1 i.e. any odd number ends with 1 and any even number ends with 0 so when we do 1 & 1 = 1 and when we do 0 & 1 = 0


This time you have learned another technique to impress your Boss, friends, professor etc.

Wait for the next trick #3
happy coding

Wednesday, 22 August 2012

Top 10 Tricks To Fool Your Java Professor

Trick #1



  1. Is your java professor always yells at you ? 
  2. Does he/she always tells you that you don't know anything about Java ?

If the answer is yes then this post is for you

Its Payback time


Next time when you meet your professor in viva or in general ask him/her a simple question 

Q. can you show me a simple program which print a NUMBER 0123 ?

if your professor is smart enough he/she will write this code 

System.out.println(123);

and gives you a explanation about why he/she has not written 0 (zero) 

if your professor in dumb (which 80% are) will end up with this code


System.out.println(0123);
So, when he will execute this code he will get output as 83
CONFUSED ???

This is because if any number is padded with initial 0 then that number is treated as Octal in Java so when you execute above code the JVM will convert the Octal to Decimal and print 83 on stdout.

So when you will explain this to your professor without the help of Google then he will be impressed :)

The problem is that most people just learn the syntax of a language and not its capability, learning syntax is very easy any moron can learn it within a month or so but learning capability takes almost years of expertise.

Wait for the next trick #2
till that time
stay hungry stay foolish

Thursday, 16 August 2012

NTSystem VS System.getProperty("user.name")

Yesterday i was reviewing my friends code, In that i found a class called NTSystem my friend was actually using this class because of this method
public String getName(); //This method gets you the current logged in user
I asked him do you think this application will work in Linux and he replied yes of course then i smiled and said try it out he tried and call me this morning and said the application is throwing
ClassNotFoundException 

why so ?


Thing is that Beginners don't understand the working, they just somehow learn (in chalega ..chalega style) or copy the code from internet the things to know is, though Java is machine independent JVM is not .
JVM is exclusive made for each OS. 

Thats why when you use NTSystem class in windows it works like a charm but the code throws an Exception when you run it on some other OS just because the JVM don't know what NTSystem is !

If you had download the JDK for Linux, there you will not find the NTSystem class.

So the bottom line is if you want to get the current logged in user in Java always use 
System.getProperty("user.name");
This Method has 2 benefits

  1. Your code will be machine independent
  2. You will get the current logged in user 



Saturday, 11 August 2012

Programatically setting wallpaper


Last week when i was doing random visit at forums I found a Question 
How to Programatically set wallpaper in windows" so i have written a code to solve this problem of that guy..... 
Setting wallpaper in windows is never this easy, all you need is my API to set & get wallpaper, this library is part of my Utilities framework and written in Java. After you have set my library in your classpath (For those who don't know how to set classpath), all you have to do is follow the below instructions


Things you should know before using this API



In windows platform when we set any image as a wallpaper, windows actually copy the image into directory "C:\Users\[username]\AppData\Roaming\Microsoft\Windows\Themes" and name it as "TranscodedWallpaper". So when ever you set any wallpaper try browsing this directory and see the result. If you haven't understand this no problem!
Go ahead and try the API you will understand the working...

  • To set wallpaper in windows just use this code 
new Wallpaper().setWallpaper( Path );
  • To get current wallpaper's path use this code
new Wallpaper().getWallpaper();

Current version 1.0 is for Windows only.

Note: Always download latest builds.