Wednesday, July 18, 2012

Performance of Appending Java Strings: "+" vs StringBuffer vs StringBuilder

There are quiet a few ways to append two Strings in java.

The most popular way to append two Strings in Java is, using the "+" operator. This is one of the costliest and inefficient operation. String objects are immutable, i.e., the contents of String objects cannot be altered. So, whenever a "+" operator is used to append two Strings, a new String with size = len(String1) + len(String2) is allocated and then the String1 and String2 are copied into the new String.

To fine tune String operations in Java applications "StringBuilder" and "Stringbuffer" classes can be used. StringBuilder is suitable for single threaded applications. StringBuffer is suitable for multithreaded applications.

The performance comparison between String appending using "+", StringBuffer and StringBuilder are shown in following graphs.



Time taken to append 100000 characters:
  • String Append using "+": ~40000 ms = 40 sec
  • String Append using StringBuffer: ~15 ms = 1/4 sec
  • String Append using StringBuilder: ~6 ms = 1/10 sec

The History of HTML5

At present most of the Websites are getting created in HTML5 and prominent Cloud players (Youtube, Scribd, Chrome Web Store, Twitter etc.) are moving to HTML5. All the famous browsers are supporting HTML5.

HTML5 Evolution

The evolution, present state and proposed future of HTML5 is well explained in following link :

http://mashable.com/2012/07/17/history-html5/

Sunday, July 15, 2012

TCP Connection Establishment: 3 Way Handshake

A TCP Connection is established between two peers before any data is transferred between them. The mechanism in which the TCP connection is established is famously termed as 3 way Handshake.



The 3 Way Handshake:

Step #1:
When the Server is in READY-TO-ACCEPT a connection, the client performs an ACTIVE-OPEN, creating by sending a SYN message to the server. The client then waits to receive an ACK for its SYN request, as well as expects to receive the Server's SYN.

Step #2:
After receiving the SYN from the client, the Server sends a single SYN+ACK message back to the client that contains an ACK for the client's SYN, and the server's own SYN.

Step #3:
The client receives the Server's SYN+ACK packet. It sends the server an ACK for the Server's SYN.

A successful TCP Connection is Established.

Wednesday, July 11, 2012

C++ Runtime Dynamic Linking using Function Name Mangling

Disclaimer: This article is for Windows Developers working with DLL

Microsoft frequently releases new version of OS and Service Packs. Along with each release, they also ship New APIs. The new APIs can be an enchancement for already existing APIs (or) the APIs can do certain functions that are specific for any newly introduced technology.

The APIs will work only in latest OS. They won't be availble in previous versions of OS. The application developed in new OS wont run in older versions, also the new API cannot be used in older Windows Versions.

Developing Windows applications that use new APIs and work in latest and older versions of Windows can be done using the Microsoft's Run Time Dynmaic Linking concept.

Run Time Dynmaic Linking:

Verifying whether an API is present in kernel32.dll and then using it or ignoring it is called Run Time Dynmaic Linking. Please refer the article in this page: http://msdn.microsoft.com/en-us/library/ms810279.aspx

Sample Code:

The code illustrates whether RegCreateKeyExW is present in kernel32.dll or not.

#include <stdafx.h>
#include <stdlib.h>
#include <windows.h>
#include <Winreg.h>

#pragma comment(lib, "Advapi32.lib")

int _tmain(int argc, _TCHAR* argv[])
{
    LONG (__stdcall *regAPI)(HKEY, LPCTSTR, DWORD, LPTSTR, DWORD, REGSAM, LPSECURITY_ATTRIBUTES, PHKEY, LPDWORD);

    if (HINSTANCE hInst = LoadLibraryW(L"kernel32.dll"))
    {
        regAPI = (LONG (__stdcall *)(HKEY, LPCTSTR, DWORD, LPTSTR, DWORD, REGSAM, LPSECURITY_ATTRIBUTES, PHKEY, LPDWORD))GetProcAddress(hInst, "RegCreateKeyExW");
        if(regAPI != NULL)
        {
            // Do Registry creation operation
        }
        else
        {
            printf("\nRegCreateKeyExW is absent in this OS. Exiting!!\n");
        }
        FreeLibrary(hInst);
    }
    
    return 0;
}

Tuesday, July 10, 2012

Dangling Pointer

C / C++ programmers should be extra cautious while handling pointers. Re-using a freed & nullified pointer causes application crash. The NULLIFIED pointer that causes the crash is named as Dangling Pointer.

Sample Code:

#include <stdio.h>
#include <string.h>

void main()
{
    char *pVal = new char[10];
    strcpy(pVal, "Hi Kingsley");

    printf("\nPrint String : %s\n", pVal);

    delete [] pVal;
    pVal = NULL; // Pointer Nullified
   
    strcpy(pVal, "Hi Kingsley"); // pVal is 'Dangling Pointer'. Copying string to it crashes the Application
}

Fixing JNI Memory Leaks


During initial stages of my coding the application that I programmed use to re-start due to Java Exception "java.lang.OutOfMemoryerror". After much analysis, we found that making frequent JNI function calls caused the java.lang.OutOfMemoryError.

Reason for the problem - JNI Memory Leak
The reference for any object created in Java and sent to JNI native functions were not de-referenced automatically. Since these objects were not de-referenced, they couldn't be cleared by GC which caused the memory leak.

Solution
Please refer following sample code to free the memory.

JNIEXPORT jobject JNICALL Java_sample_package_SampleJavaClass_classMethod
(JNIEnv * env, jobject obj, jstring jstrString)
{
    const jchar* szString = (jchar*)env->GetStringChars(jstrString, 0);
    env->ReleaseStringChars(jstrString, (const jchar *)szString);
   
    // De-Referencing the String object
    env->DeleteLocalRef(jstrString);
}


Results
Considerable amount of Memory Leaks were fixed. Throughput is not 100%. 

Additional Reference:
http://www.dynamicobjects.com/d2r/archives/001816.html


Monday, July 9, 2012

Abstract classes and Abstract Methods in Java

Abstract Methods:
  • They are present in abstract classes
  • The keyword "abstract" is prepended to the methods
  • Abstract methods are implemented only in sub-class / inherited class and not in "Abstract" class
  • Since abstract methods are implemented in sub-class, the return type of abtract methods is either "protected" or "public"

Abstract Classes:
  • A class that contains "abstract" methods is an abstract class
  • Abstract classed can contain "non static" and "non final" member variables
  • They can NEVER be instantiated. They can be ONLY INHERITED
  • One abstract class can inherit another abstract class
  • Abstract classes can contain ordinary methods as well as abstract methods
Sample Implementation:


/**
 * ABSTRACT CLASS
 * /
public abstract class AbstractTest {
    public abstract void testPrint1();
    protected abstract void testPrint2();
}

/**
 * ABSTRACT CLASS IMPLEMENTED

 * NOTE: IMPL CLASS MUST IMPLEMENT ALL ABSTRACT METHODS IN ABSTRACT CLASS
 */

public class AbstractTestImpl extends AbstractTest {
    public void testPrint1() {
        System.out.println("Test Print One!");
    }

    public void testPrint2() {
        System.out.println("Test Print Two!");
    }

    public static void main(String args[]) {
        AbstractTestImpl obj = new AbstractTestImpl();
        obj.testPrint1();
    }
}

Friday, July 6, 2012

Race Condition vs Deadlock

Race Condition & Deadlock are not the same. Please refer following examples to understand the differences.
 
Race Condition: When two threads randomly tries to update a common variable.
 
Eg: 

  1. Var1 = 100
  2. Thread T1 & Thread T2 reads Var1 at same time
  3. But, T2 updates Var1 to 120 & exits
  4. Then, T1 updates Var1 to 150 & exits
  5. This leads to confused result for Var1
[Expected result is 100 + 20 + 50 = 170]

 
Dead Lock: Two thread waiting without end
 

Eg:
  • Var1 is locked & used by Thread T1.
  • Var2 is locked & used by Thread T2.
  • T1 waits for Var1 to be released & T2 waits for Var2 to be released leading to dead lock.
http://support.microsoft.com/kb/317723