Tuesday, August 31, 2010

Java Collections Framework


List<E>
Implementations: LinkedList<E>, ArrayList<E>, Vector<E>, Stack<E>

A List<E> is a collection which can contain duplicate elements, and the elements are ordered (like an array, you can add an element at a specific position, and the elements are accessed using their index).

[Stack<E> has come up in the examination in the past, so here is some information on it.

Stack<E> is a subset of Vector<E>, which contains some extra methods. The idea of a stack is like its name, it acts like a piled up stack of items: When you add an element, it goes to the top of the stack, and when you extract an element, it is taken off the top. In other words, this is a last-in, first-out system. The methods are:

push(object) - Add an element onto the top of the stack.
pop() - Removes the object at the top of this stack and returns that object as the value of this function.
peek() - Looks at (i.e. returns) the object at the top of this stack without removing it from the stack.. ]



Set<E>
Implementations: Hashset<E>

A Set<E> is a collection which cannot contain any duplicate elements and has no explicit order to its elements (unlike array, where every element exists at a particular index i.e. MyArray[15]).

SortedSet<E>
Implementations: TreeSet<E>

A SortedSet<E> is a Set<E> which maintains its elements in ascending order.



Map<K, V>
Implementations: HashMap<K, V>, Hashtable<K, V>, WeakHashMap<K, V>

Maps keys to values. In other words, for every key, there is a corresponding value, and you look up the values using the keys. Maps cannot have duplicate keys, and each key maps to at most one value.

Note: A Map<K, V> does not implement the Collection interface.

SortedMap<K, V>
Implementations: TreeMap<K, V>

A SortedMap<K, V> is a Map<K, V> which maintains its mapping in ascending key order.



add() method is available for any type of Collection classes only
TreeMap<K, V> is a java.util.Map<K, V>, use put() method with 2 arguments. This is due to Map<K, V> does not implement the Collection interface.




Thread-safe and slowest iteration speed
Hashtable, Vector

NON thread-safe
ArrayList, HashSet, HashMap, LinkedList, TreeSet, LinkedHashSet, TreeMap





Object Ordering

Implementations of the SortedSet and SortedMap interfaces sort their elements. To determine what criterion is used to sort the elements you can use either the Comparable or Comparator interfaces. Using Comparable means that the classes that you put in your SortedSet or SortedMap implement the Comparable interface, which just means that they contain a method compareTo() which determines whether the object is "greater" or "less than" another object. To use the Comparator interface, you pass an object which implements Comparator to your SortedSet or Sorted map, and it will use the Comparator for ordering.




Distinguish between correct and incorrect implementations of hashCode() methods.

The hashCode() value of an object gives a number which can be used to in effect to 'index' objects in a collection. A collection class can group its objects by their hashcodes, and if you called e.g. contains() (or get() in case of a Map), it can first find the group based on the hashcode, then search that group. This avoids the need to check every object in the collection.

The requirements of a hashCode() implementation are that if two objects are equal as determined by the equals() method, their hashcodes should be the same. This is why wherever you override the equals() method, you should override hashCode() as well.

The reverse is not required i.e. it is permitted for two objects that are not equal to have the same hashcode. This makes sense, as it is not always possible to ensure unique hashcodes. The method returns an integer and there are only an finite number of integer values to use. However, where possible, it is desirable to have the hashcodes be distinct as this can improve performance. If the hashcodes can be well distributed (i.e. scattered throughtout the integer range) as well, all the better.




BitSet

For completeness, here is some information on BitSet, which isn't part of the Collections Framework, but may be examinable:
A BitSet contains elements which are bits, i.e. of the boolean primitive type. Like, for example, a Vector, and unlike an array, a BitSet does not have a fixed size, and grows as needed when you add elements to it.






(^_^)





Monday, August 30, 2010

JAVA strictFP


A new keyword in Java2 is strictfp. strictfp is not in versions of Java prior to Java2.

strictfp is a keyword and can be used to modify a class or a method, but never a variable. Marking a class as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating points.

It is included here for completeness, however, I cannot say whether it is examinable and you will have to look elsewhere for information on its syntax. This modifier tells the compiler to use a strict form of floating point calculations, which ensures an identical result on every platform. In Java 1.1, this strict form is always used, but in Java2, when you do not specify strictfp, the Java virtual machine can do a fast calculation, which makes the most of the performance of the native processor without the overhead of converting to a consistent cross-platform format.

[Technical aside, for those interested in microprocessors:
I believe part of the reason for its introduction is that the X86 CPUs have an 80bit FPU, versus 64bits used in the Java standard and on Suns processors. Intel complained that this gave their CPUs a disadvantage in Java]

Reference



(*_*)

Thursday, August 19, 2010

Vector or ArrayList


Sometimes Vector is better; sometimes ArrayList is better; sometimes you don't want to use either. I hope you weren't looking for an easy answer because the answer depends upon what you are doing. There are four factors to consider:

* API
* Synchronization
* Data growth
* Usage patterns

Let's explore each in turn.

API

In The Java Programming Language (Addison-Wesley, June 2000) Ken Arnold, James Gosling, and David Holmes describe the Vector as an analog to the ArrayList. So, from an API perspective, the two classes are very similar. However, there are still some major differences between the two classes.

Synchronization

Vectors are synchronized. Any method that touches the Vector's contents is thread safe. ArrayList, on the other hand, is unsynchronized, making them, therefore, not thread safe. With that difference in mind, using synchronization will incur a performance hit. So if you don't need a thread-safe collection, use the ArrayList. Why pay the price of synchronization unnecessarily?

Data growth

Internally, both the ArrayList and Vector hold onto their contents using an Array. You need to keep this fact in mind while using either in your programs. When you insert an element into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. It's always best to set the object's initial capacity to the largest capacity that your program will need. By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don't know how much data you'll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.

Usage patterns

Both the ArrayList and Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container. All of these operations can be performed in constant time -- O(1). However, adding and removing elements from any other position proves more expensive -- linear to be exact: O(n-i), where n is the number of elements and i is the index of the element added or removed. These operations are more expensive because you have to shift all elements at index i and higher over by one element. So what does this all mean?

It means that if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. If you want to do anything else to the contents, go find yourself another container class. For example, the LinkedList can add or remove an element at any position in constant time -- O(1). However, indexing an element is a bit slower -- O(i) where i is the index of the element. Traversing an ArrayList is also easier since you can simply use an index instead of having to create an iterator. The LinkedList also creates an internal object for each element inserted. So you have to be aware of the extra garbage being created.


( (*_*) )


Hashtable, HashMap, HashSet

I was reading about collection framework of JAVA. And was studying Hashtable, HashMap and HashSet. Its quite interesting to know the differences between them. In this post I will discuss these three with examples.

Hashtable

Hashtable is basically a data structure to retain values of key-value pair.

* It didn’t allow null for both key and value. You will get NullPointerException if you add null value.
* It is synchronized. So it comes with its cost. Only one thread can access in one time

1 Hashtable cityTable = new Hashtable();
2 cityTable.put(1, "Lahore");
3 cityTable.put(2, "Karachi");
4 cityTable.put(3, null); /* NullPointerEcxeption at runtime */
5
6 System.out.println(cityTable.get(1));
7 System.out.println(cityTable.get(2));
8 System.out.println(cityTable.get(3));


HashMap

Like Hashtable it also accepts key value pair.

* It allows null for both key and value
* It is unsynchronized. So come up with better performance


1 HashMap productMap = new HashMap();
2 productMap.put(1, "Keys");
3 productMap.put(2, null);


HashSet

HashSet does not allow duplicate values. It provides add method rather put method. You also use its contain method to check whether the object is already available in HashSet. HashSet can be used where you want to maintain a unique list.

1 HashSet stateSet = new HashSet();
2 stateSet.add ("CA");
3 stateSet.add ("WI");
4 stateSet.add ("NY");
5
6 if (stateSet.contains("PB")) /* if CA, it will not add but shows following message */
7 System.out.println("Already found");
8 else
9 stateSet.add("PB");


<<< >>>

Oracle Processes and Session


There is an important parameter is "processes" and this specifies the maximum number of operating system user processes that can simultaneously connect to Oracle.

I am sure you can increase this parameter more than 150 (current by default is 150) or more, but maximum limit depend on operation systems MEM or HDD space.

To increase, login to

sqlplus "/ as sysdba"
SELECT COUNT(*) FROM v$session;
SHOW PARAMETER SESSIONS --this return current value use below command increase this
ALTER SYSTEM SET SESSIONS= SCOPE=SPFILE;
SHOW PARAMETER PROCESSES --this return current value use below command increase this
ALTER SYSTEM SET PROCESSES= SCOPE=SPFILE;
shutdown immediate;
startup;


<< (*_*) >>

Sunday, August 15, 2010

JVM 64-bit

What it is:

A 64-bit version of Java has been available to Solaris SPARC users since the 1.4.0 release of J2SE. A 64-bit capable J2SE is an implementation of the Java SDK (and the JRE along with it) that runs in the 64-bit environment of a 64-bit OS on a 64-bit processor. You can think of this environment as being just another platform to which we've ported the SDK. The primary advantage of running Java in a 64-bit environment is the larger address space. This allows for a much larger Java heap size and an increased maximum number of Java Threads, which is needed for certain kinds of large or long-running applications. The primary complication in doing such a port is that the sizes of some native data types are changed. Not surprisingly the size of pointers is increased to 64 bits. On Solaris and most Unix platforms, the size of the C language long is also increased to 64 bits. Any native code in the 32-bit SDK implementation that relied on the old sizes of these data types is likely to require updating.

Within the parts of the SDK written in Java things are simpler, since Java specifies the sizes of its primitive data types precisely. However even some Java code needs updating, such as when a Java int is used to store a value passed to it from a part of the implementation written in C.

What it is NOT:

Many Java users and developers assume that a 64-bit implementation means that many of the built-in Java types are doubled in size from 32 to 64. This is not true. We did not increase the size of Java integers from 32 to 64 and since Java longs were already 64 bits wide, they didn't need updating. Array indexes, which are defined in the Java Virtual Machine Specification, are not widened from 32 to 64. We were extremely careful during the creation of the first 64-bit Java port to insure Java binary and API compatibility so all existing 100% pure Java programs would continue running just as they do under a 32-bit VM.

Will 32-bit native code work with a 64-bit VM?

No. All native binary code that was written for a 32-bit VM must be recompiled for use in a 64-bit VM. All currently supported operating systems do not allow the mixing of 32 and 64-bit binaries or libraries within a single process. You can run a 32-bit Java process on the same system as a 64-bit Java process but you cannot mix 32 and 64-bit native libraries.

What are the performance characteristics of 64-bit versus 32-bit VMs?

Generally, the benefits of being able to address larger amounts of memory come with a small performance loss in 64-bit VMs versus running the same application on a 32-bit VM. This is due to the fact that every native pointer in the system takes up 8 bytes instead of 4. The loading of this extra data has an impact on memory usage which translates to slightly slower execution depending on how many pointers get loaded during the execution of your Java program. The good news is that with AMD64 and EM64T platforms running in 64-bit mode, the Java VM gets some additional registers which it can use to generate more efficient native instruction sequences. These extra registers increase performance to the point where there is often no performance loss at all when comparing 32 to 64-bit execution speed.

The performance difference comparing an application running on a 64-bit platform versus a 32-bit platform on SPARC is on the order of 10-20% degradation when you move to a 64-bit VM.

On AMD64 and EM64T platforms this difference ranges from 0-15% depending on the amount of pointer accessing your application performs.

Which garbage collector should I use for a very large 64-bit heaps?

The major advantage of a 64-bit Java implementation is to be able to create and use more Java objects. It is great to be able to break these 2GB limits. Remember, however, that this additional heap must be garbage collected at various points in your application's life span. This additional garbage collection can cause large pauses in your Java application if you do not take this into consideration. The Hotspot VM has a number of garbage collection implementations which are targetted at Java applications with large heaps. We recommend enabling one of the Parallel or Concurrent garbage collectors when running with very large heaps. These collectors attempt to minimize the overhead of collection time by either collecting garbage concurrent with the execution of your Java application or by utilizing multiple CPUs during collections to ge the job done faster.

For more information on these garbage collection modes and how to select them please refer to the Hotspot GC tuning guide which can be found here: Tuning Garbage Collection with the 5.0 Java Virtual Machine (http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html)


(^__^)

JVM JIT Compiler

JAVA JVM JIT Compiler

What is the difference between the -client and -server systems?

These two systems are different binaries. They are essentially two different compilers (JITs) interfacing to the same runtime system. The client system is optimal for applications which need fast startup times or small footprints, the server system is optimal for applications where the overall performance is most important. In general the client system is better suited for interactive applications such as GUIs. Some of the other differences include the compilation policy, heap defaults, and inlining policy.

Where do I get the server and client systems?

Client and server systems are both downloaded with the 32-bit Solaris and Linux downloads. For 32-bit Windows, if you download the JRE, you get only the client, you'll need to download the SDK to get both systems.

For 64-bit, only the server system is included. On Solaris, the 64-bit JRE is an overlay on top of the 32-bit distribution. However, on Linux and Windows, it's a completely separate distribution.

I would like java to default to -server. I have a lot of scripts which I cannot change (or do not want to change). Is there any way to do this?

Since Java SE 5.0, with the exception of 32-bit Windows, the server VM will automatically be selected on server-class machines. The definition of a server-class machine may change from release to release, so please check the appropriate ergonomics document for the definition for your release. For 5.0, it's Ergonomics in the 5.0 Java[tm] Virtual Machine. (http://www.oracle.com/technetwork/java/ergo5-140223.html).

Should I warm up my loops first so that Hotspot will compile them?

Warming up loops for HotSpot is not necessary. HotSpot contains On Stack Replacement technology which will compile a running (interpreted) method and replace it while it is still running in a loop. No need to waste your applications time warming up seemingly infinite (or very long running) loops in order to get better application performance.


(*$$*)__(^$$^)

Saturday, August 7, 2010

yum

Often use when people want to use install or update software using the command line in LINUX. For this you use a program called "yum".

First become root, and then you can use the following commands:

* To see a list of available software:

yum list available

* To install some software, you type:

yum install packagename

* To update some software, you type:

yum update packagename

If you leave out "packagename" yum will update all your software.

* To see what updates are available, you can do:

yum check-update

* To search for a package, you can do:

yum search word

For more info about yum, see the yum project page, http://yum.baseurl.org/.



(*_*)

Chinese Support on Linux

Chinese Support on Red Hat / CentOS

You can easily add Chinese support to CentOS by installing the following packages:

# yum -y install scim-chinese-standard scim-tables-chinese
# yum -y install fonts-chinese openoffice.org-langpack-zh_TW

Please do the following to enable the Chinese Support, you can even view Chinese when you are logged in English session.

Login to root, type:

# yum groupinstall "Chinese Support"

and you will get all the necessary Chinese language support packages for the application, like OpenOffice and Firefox, installed on your system.

You can also use the same command for Japanese or Korean. It would be like the following.

# yum groupinstall "Japanese Support"

or

# yum groupinstall "Korean Support"

To change the language configuration after you have completed the installation, use the Language Configuration Tool.

# system-config-language



*************************************

Monday, August 2, 2010

google appengine date formatting using JSTL


JSTL can be very useful for date formatting in JSP pages. In order to make sure JSTL is working in Google App Engine, please set this in each JSP pages or TAG files,

<%@ page isELIgnored="false"%>
<%@ tag isELIgnored="false"%>

For various sample of date formatting,

<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<%@ page isELIgnored="false"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

<html>
<head>
<title>Format Date</title>
</head>

<body>
<c:set var="now" value="<%=new java.util.Date()%>" />

<table border="1" cellpadding="0" cellspacing="0"
style="border-collapse: collapse" bordercolor="#111111" width="63%"
id="AutoNumber2">
<tr>
<td width="100%" colspan="2" bgcolor="#0000FF">
<p align="center"><b> <font color="#FFFFFF" size="4">Formatting:
<fmt:formatDate value="${now}" type="both" timeStyle="long"
dateStyle="long" /> </font> </b></p>
</td>
</tr>

<tr>
<td width="51%">formatDate type="time"</td>
<td width="49%"><fmt:formatDate type="time" value="${now}" /></td>
</tr>

<tr>
<td>type="date"</td>
<td><fmt:formatDate type="date" value="${now}" /></td>
</tr>

<tr>
<td>type="both"</td>
<td><fmt:formatDate type="both" value="${now}" /></td>
</tr>

<tr>
<td>type="both" dateStyle="default" timeStyle="default"</td>
<td><fmt:formatDate type="both" dateStyle="default"
timeStyle="default" value="${now}" /></td>
</tr>

<tr>
<td>type="both" dateStyle="short" timeStyle="short"</td>
<td><fmt:formatDate type="both" dateStyle="short"
timeStyle="short" value="${now}" /></td>
</tr>

<tr>
<td>type="both" dateStyle="medium" timeStyle="medium"</td>
<td><fmt:formatDate type="both" dateStyle="medium"
timeStyle="medium" value="${now}" /></td>
</tr>

<tr>
<td>type="both" dateStyle="long" timeStyle="long"</td>
<td><fmt:formatDate type="both" dateStyle="long" timeStyle="long"
value="${now}" /></td>
</tr>

<tr>
<td>type="both" dateStyle="full" timeStyle="full"</td>
<td><fmt:formatDate type="both" dateStyle="full" timeStyle="full"
value="${now}" /></td>
</tr>

<tr>
<td>pattern="yyyy-MM-dd"</td>
<td><fmt:formatDate pattern="yyyy-MM-dd" value="${now}" /></td>
</tr>

</table>

</body>
</html>


Deploy this JSP in GAE, to see the actual result.

To show date and time in your timezone, say for example GMT+8:00, please set the following in web.xml

<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.timeZone</param-name>
<param-value>GMT+8:00</param-value>
</context-param>


Thank You!

About

My photo
Petaling Jaya, Selangor, Malaysia