Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, March 13, 2011

Serializing / De-serializing bean object using XMLEncoder / XMLDecoder

The java.beans package provides very useful classes [XMLEncoder / XMLDecoder] to save an object state [persist] into an XML file [Serialize] and easily read it back [De-serialize]. It's very helpful while debugging the state of objects especially in the production environments.


No need to provide any examples as the below are some useful links that already contains the same:

Monday, November 9, 2009

J2SE 5.0 reached its End of Service Life (EOSL) Notice

On November 3, 2009, J2SE 5.0 reached its End of Service Life (EOSL), which is the date of final publicly available update of version 5.0 (i.e. J2SE 5.0 Update 22).

You can find more information here.
Learn more about EOL policy here.

Thursday, September 24, 2009

Code Kata by Dave Thomas

Dave Thomas took the idea of coding practice and made something very well, pragmatic out of it.
There are series of katas, which are small, thought-provoking exercises that programmers can do in the language of their choice.

You can find it here. Really worth giving a try :)

Friday, June 26, 2009

Chaining methods using power of "return this"

In one of my older post [here], I discussed about the power of Fluent Interfaces. We can use those in building method chaining, thus improving the readability of code just english-like sentences.

We can also implement this using "return this" in class methods.

Take a look at below source code:

Bug.java



CreateBugs.java



Output:



The above programs are self explanatory :)

Monday, May 25, 2009

To overcome "Maximum open cursors exceeded" issue

When we execute a query in oracle, a ResultSet is created and stored in the memory. Oracle allows the programmer to access this ResultSet in the memory through cursors.

When we fire SELECT query / DML query from Java code, Oracle returns the reference of this created cursor to the Java program, which we refer as a ResultSet. Following is the hierarchy of creating objects in JDBC:



[For DML queries, we don't require "ResultSet" object]

Now, when we execute this query in loop for multiple records, we can use the same "Connection" object, but we'll have to close ResultSet object and Statement object at the end of each loop.

[Here we're using distributed database connection which means for each request, we create new "Connection" object and after the request is processed, we close this "Connection" object. Now, there might be the case that for one request, we need to fire multiple SELECT / DML queries, so we use the same "Connection" object to process this request.]



Closing ResultSet object and Statement object at the end of each loop will make sure that the cursors opened by executing this query will be closed / released.

[For DML queries, we need to close only "Statement" object].

Finally we close the connection object when we finish executing the queries in loop.



All the resources (including cursors) are released when the "Connection" object is closed.

Following this, we'll never encounter "Maximum open cursors exceeded" issue in any application :)

Wednesday, February 11, 2009

Maintaining and Managing variables stored in application's session

In one of our project, we were storing frequently used application related data into the session, but now as the project is growing incrementally, storing new data / modifying existing data into session has became very confusing and difficult to manage.

I was just thinking about the workaround for coming out of this havoc, and voila, I got one :). This workaround I've implemented in our project. I would like to share the idea which brought us out of this mess.

Idea (Workaround): We can use one singleton java class, which has one HashMap variable. There will be custom methods for getting, setting and removing (operations same as that of session operations) values from HashMap. Now we can use this implementation for storing data (which was supposed to be stored into the session) into the HashMap present in this class, and then we can put the object of this java class (we'll be having one object for each session) into the session. So, at the session level, there will be only one object present in the session, and now it's lot easy to maintain and manage session variables (now HashMap data). Also, there will be only two session operations in each class, first: getting this java class object from session, second: storing back this java class object back to the session.

Implementing this thing was really fun and gave us lot of flexibility to maintain and manage session variables... :)

Thursday, February 5, 2009

-C-O-N-C-E-P-T- Series : Java

Difference between using "" and toString() method for converting object value to String:

Case I - Using "":

-----------------------------------------------------------------
BigDecimal dec = new BigDecimal("1234567");
String str = "" + dec; // converting dec to String
System.out.println("str: "+str);

o/p:
str: 1234567
-----------------------------------------------------------------

-----------------------------------------------------------------
BigDecimal dec = null;
String str = "" + dec; // converting dec to String
System.out.println("str: "+str);

o/p:
str: null
-----------------------------------------------------------------


Case II - Using toString() method:

-----------------------------------------------------------------
BigDecimal dec = new BigDecimal("1234567");
String str = null;

if( dec!=null ) {
str = dec.toString(); // converting dec to String
}

System.out.println("str: "+str);

o/p:
str: 1234567
-----------------------------------------------------------------

-----------------------------------------------------------------
BigDecimal dec = null;
String str = null;

if( dec!=null ) {

str = dec.toString(); // converting dec to String
}

System.out.println("str: "+str);

o/p:
str: null
-----------------------------------------------------------------

In first case, we don't require null check, but doesn't has readability.
In second case, we require null check, but has readability.

Each one has its own ease of use.

Saturday, January 3, 2009

Custom Map Implementation in Java

Blogging after a long-long-long-... time :)

When we fetch records from HashMap, it gives records according to hash code, i.e. the records returned are not in the order when they're placed in the Map.

When we fetch records from TreeMap, it gives records in the sorted order of key, i.e. the records returned are not in the order when they're placed in the Map.

What I want was a Map that should return sequential values/objects that are put into when they're fetched. So, why not to make our own custom implementation of Map that does what is needed.

I constructed following Custom Map Implementation. Please find the code below:

CustomMapImpl.java



===
Supporting Class: CustomEntrySetImpl.java



===

Output of above program:

key1 : value1
key2 : value2
key4 : value4
key5 : value5
key6 : value6
key7 : value7

---

It was a very great experience. I also digged into the actual Java Map source code which was an amazing experience.


Wednesday, August 27, 2008

Using "synchronization" effectively

"Synchronization is anti-performance. So how can we use synchronization and still optimize on performance? So apply synchronization where it is absolutely necessary, or as minimum as possible."


We'll consider following two code snippets:

Scenario: Creating/accessing singleton object

Method level synchronization:



As you can see, the "synchronized" keyword is used at method level. So, now in multi-threaded environment, multiple threads accessing the getInstance() method will be queued-in. Following figure shows the scenario:



As shown in above figure, thread "t1" (the thread that is allowed to enter the getInstance() method first) will create the first object of "DemoClass" class and other threads will just get the reference of that singleton object which was created by thread "t1". Now this will definitely hamper the application's performance as every thread after "t1" will be queued-in, as there is no need after the singleton object is been created. So, we can use "synchronized" at block level which will reduce this performance bottle-neck. How, we'll see it soon :)

Block level synchronization:



As you can see, the "synchronized" keyword is used at block level. So, now in multi-threaded environment, multiple threads accessing the getInstance() method will NOT be queued-in. Following figure shows the scenario:



As shown in above figure, multiple threads can simultaneously access the getInstance() method. But, it can be that more than one threads can simultaneously hit the first "if statement". So, we can use "synchronized" keyword inside "if" such that those number of threads which are arrived parallel-ly can be queued-in. The second "if statement" makes sure that only one object is created as we're dealing with singleton class. Now, multiple threads can parallel-ly access the getInstance() method to get the reference of a singleton object. This removes the performance bottle-neck as mentioned in the above scenario.

Cool concept, isn't it :)

Thursday, July 31, 2008

Updating the state of a Singleton Object after specific interval of time

I've created a Singleton Object which holds some values which are fetched from the database table. Following are the class specs:

1) All setter methods are private
2) All getter methods are public
3) One configuration method that sets all the values in the related attributes of class using their private setters

The need was to update the state of this singleton object when there are any changes made in the configuration table in the database. But to achieve this, I need to restart the server each time when any changes has been made in the configuration table.

So I created one WatchDog class in a thread that continuously changes the state of a singleton configuration object after a specific interval of time, & this time interval in-turn is fetched dynamically from the same configuration table from the database :)

Thursday, July 3, 2008

-C-O-N-C-E-P-T- Series : Java

Synchronizing a static method and its effect in the multi-threading environment:

Since static code can modify only the static data, you will protect a static data with synchronized keyword. We know that static data and methods have only one copy for all the objects of that class. Therefore, you only need one lock per class to synchronize static methods. Object locks are not required for static methods. Static methods use a class lock for synchronization. This special lock is also an object lock.

Consider following java code:


Fig1


Fig2

Both the figure above are self explanatory, but I would like to elaborate more on Fig2. When we synchronize an instance method, the thread accessing that method acquires "Object Lock" on the object such that no other thread can access that method unless it completes its execution. Now for "synchronized static" method, it acquires "Class Lock" on that class. This class lock also implicitly has object lock, it's because as non-static methods can modify static variables, so we need to also put a lock on synchronized instance variables & this is internally done by the class lock.
Hence if one thread is executing a static synchronized method of a class then it holds a lock on all other synchronized methods of that class and in effect no other thread can call any of the synchronized static methods of that class until this current thread releases the lock.

This concept is really very interesting to learn :)

Stay tuned... :)

Tuesday, June 24, 2008

-C-O-N-C-E-P-T- Series : Java

Object's Shallow Copy and Deep Copy in Java:


Understanding concept:
Suppose I have following two objects:



Shallow copy: "obj2" refers to the memory block pointed by "obj1" as shown below.



Deep Copy: Here the data is actually copied over from "obj1" to "obj2" as shown below.



Java code:



(You can click on image to enlarge it)

Output:



Any comments are always welcome :)

Thursday, June 19, 2008

-C-O-N-C-E-P-T- Series : Java

Enhanced for loop:

Code snippet:




Output of the program is:
4
0
0
3
0




Here, "i" is directly assigned the each value from array in each iteration.
Iteration 1: Value of i = 1 (arr[0])
Iteration 2: Value of i = 2 (arr[1])
Iteration 3: Value of i = 3 (arr[2])
Iteration 4: Value of i = 4 (arr[3])



The above diagram is self-explanatory. Really interesting concept & worth learning :)

Wednesday, June 18, 2008

Implemented "SessionListener"

Blogging after a long time :)

Today I implemented Session Listener in our Project. Actually our requirement was to do certain database clean-up after the session time-out takes place. We could have called a Struts action when user clicks on Logout button, but the problem was - if the user closes the browser directly or forcefully closes the browser through Windows Task Manager, then how to call the clean-up code, so there was a need such that this code gets run by the server automatically after the session is about to time-out.

So I wrote a SessionListener class that implements HttpSessionListener. It's really a very cool concept that keeps track of each & every users' session. Even if you close the client browser, the required clean-up code will be fired automatically by the server itself & there you'll also have the access of that respective session data for that particular user :)


Any comments are always welcome :)

Wednesday, March 12, 2008

-C-O-N-C-E-P-T- Series : Making simultaneous AJAX calls to the same servlet

AJAX calls are "asynchronous" in nature. So what does this mean? You can have multiple requests to same (or different) servlets with each request processed asynchronously. Right, so are you speaking anything new?? Yes I am :) When you make simultaneous AJAX calls to the same servlet, the last call overlaps the response text with the previous, so as a result you get only the last requet's response text i.e. HTTP requests are overlaped. I faced this this problem in one of our Project, so I thought to share some views on it.

Examples:

Traditional code:


function ajaxRequest() {
...
myRequest.onreadystatechange = callBack; // assign callback function
...
}

function callBack() {
if (myRequest.readyState == 4) {
if (myRequest.status == 200) {
// Update DOM
}
}
}


Rearranging the above code:

Now we make some rearrangement of the AJAX code so that multiple HTTP requests can go on simultaneously. To do this, the XMLHTTP request object must be instantiated inside the Javascript function that calls the server. Furthermore, all code related to the request must be inside this function. The callback function must be an anonymous inner function within the ajaxRequest() function, and the code which updates the page after the callback must also be within the anonymous inner function.


function ajaxRequest() {
...
myRequest.onreadystatechange = function()
{
if (myRequest.readyState == 4)
{
if (myRequest.status == 200)
{
// update DOM with results
}
}
} // end anonymous inner function (callback)
...
}


Doing this I was able to handle multiple AJAX calls simultaneously.

Please feel free to correct me at any point :)

Wednesday, February 27, 2008

Preventing Cross Site Scripting (XSS) Attacks

I came across very nice & informative article by Greg Murray on his blog here.
He had explained the XSS attacks & how to prevent them very nicely. Really worth reading :)

Tuesday, February 26, 2008

-C-O-N-C-E-P-T- Series : Java

<CONCEPT>

Casting String to Boolean in Java:

We can achieve this using the Boolean class' static method:
Boolean.parseBoolean(String s) - returns a boolean value

Sample code:


String str = "true";
if( Boolean.parseBoolean(str) ){
    System.out.println("Value is true");
} else{
    System.out.println("Value is false");
}


Casting Boolean to String in Java:

We can achieve this using the String class' static method:
String.valueOf(boolean b) - returns the string representation of the boolean argument

Sample code:


boolean blnFlag = true;
String strVal = String.valueOf(blnFlag);

</CONCEPT>

Saturday, February 2, 2008

Using JConsole to monitor and manage JVMs

In-built monitoring and management support:
The J2SE 5.0 release provides built-in comprehensive monitoring and management support. It not only defines the management interfaces for the Java virtual machine, but also provides out-of-the-box remote monitoring and management on the Java platform and of applications that are running on it.
Also the JDK 5.0 includes the Java Monitoring and Management Console (JConsole) tool. It uses the extensive instrumentation of the Java virtual machine to provide information on performance and resource consumption of applications running on the Java platform using Java Management Extension (JMX) technology.

What is JConsole?
It's a JMX-compliant graphical tool for monitoring a Java virtual machine. It can monitor both local and remote JVMs.

I tried monitoring both local & remote JVMs. Really it's a very useful tool that helps user know the memory used by their application & many other important things. It is useful for both, a developer & a tester.

I've started exploring more on this tool as it'll be very much helpful in our Projects which will make them more efficient. I'll regularly post my experiences regarding my future explorations. Keep visiting :)

Thursday, November 1, 2007

Saturday Project...

I just came across the article written by Geertjan Wielenga (here) & it was worth reading it. Maybe I'll start to implement some sort of a pet project in Java which I'll open source it later. I am really very passionate for contributing to Open Source :)

Thursday, October 25, 2007

Implementing Fluent Interface in Java

Yesterday my friend Neeraj came across the concept (?) called "Fluent Interface". He told that he successfully implemented it in Java. Today I read lot of articles on it, and finally I was too successful to implement it in Java using a very-very simple program.

About Fluent Interface:
Fluent Interface is used to create a readable model i.e. to convert APIs to English-like sentences. It is slightly harder to write but much easier to read.

"Martin Fowler coined the term "FluentInterface" to describe objects that expose an interface that flows, and is designed to be readable and concise. The cost of this fluency is additional effort required to design the interface for your object and the slight increase in complexity. These types of interfaces are often utilized to create configurations for your objects but can progress into an internal Domain Specific Language or DSL." [Excerpt from Randy Patterson's blog post ]

Some useful pointers:
http://www.martinfowler.com/bliki/FluentInterface.html
http://www.bofh.org.uk/articles/2005/12/21/fluent-interfaces


_________________________________________________________________________________________________________________

"Look at the sky. We are not alone. The whole Universe is friendly to us and conspires only to give the best to those who dream and work."

- Dr. A P J Abdul Kalam
_________________________________________________________________________________________________________________