Tuesday, 20 November 2012

Smart questions


The original question was How to count the number of 1's a number will have in binary? I included a performance comparison of using Integer.bitCount() which can be turned into an intrinic i.e. a single machine code instructionPOPCNT and the Java code which does the same thing.

Question

How do I count the number of 1's a number will have in binary?
So let's say I have the number 45, which is equal to 101101 in binary and has 4 1's in it. What's the most efficient way to write an algorithm to do this?

Answer

Instead of writing an algorithm to do this it's best to use the built in function. Integer.bitCount()

What makes this especially efficient is that the JVM can treat this as an intrinsic. i.e. recognise and replace the whole thing with a single machine code instruction on a platform which supports it e.g. Intel/AMD

To demonstrate how effective this optimisation is

public static void main(String... args) {
    perfTestIntrinsic();

    perfTestACopy();
}

private static void perfTestIntrinsic() {
    long start = System.nanoTime();
    long countBits = 0;
    for (int i = 0; i < Integer.MAX_VALUE; i++)
        countBits += Integer.bitCount(i);
    long time = System.nanoTime() - start;
    System.out.printf("Intrinsic: Each bit count took %.1f ns, countBits=%d%n", (double) time / Integer.MAX_VALUE, countBits);
}

private static void perfTestACopy() {
    long start2 = System.nanoTime();
    long countBits2 = 0;
    for (int i = 0; i < Integer.MAX_VALUE; i++)
        countBits2 += myBitCount(i);
    long time2 = System.nanoTime() - start2;
    System.out.printf("Copy of same code: Each bit count took %.1f ns, countBits=%d%n", (double) time2 / Integer.MAX_VALUE, countBits2);
}

// Copied from Integer.bitCount()
public static int myBitCount(int i) {
    // HD, Figure 5-2
    i = i - ((i >>> 1) & 0x55555555);
    i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
    i = (i + (i >>> 4)) & 0x0f0f0f0f;
    i = i + (i >>> 8);
    i = i + (i >>> 16);
    return i & 0x3f;
}

prints

Intrinsic: Each bit count took 0.4 ns, countBits=33285996513
Copy of same code: Each bit count took 2.4 ns, countBits=33285996513

Map Traversal ( Collection)

How to Traverse Map in different ways


package com.mkyong;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
 
public class LoopMap {
 
  public static void main(String[] args) {
 
 // initial a Map
 Map<String, String> map = new HashMap<String, String>();
 map.put("1", "Jan");
 map.put("2", "Feb");
 map.put("3", "Mar");
 map.put("4", "Apr");
 map.put("5", "May");
 map.put("6", "Jun");
 
 System.out.println("Example 1...");
 // Map -> Set -> Iterator -> Map.Entry -> troublesome
 Iterator iterator = map.entrySet().iterator();
 while (iterator.hasNext()) {
  Map.Entry mapEntry = (Map.Entry) iterator.next();
  System.out.println("The key is: " + mapEntry.getKey()
   + ",value is :" + mapEntry.getValue());
 }
 
 System.out.println("Example 2...");
 // more elegant way
 for (Map.Entry<String, String> entry : map.entrySet()) {
  System.out.println("Key : " + entry.getKey() + " Value : "
   + entry.getValue());
 }
 
 System.out.println("Example 3...");
 // weired way, but work anyway
 for (Object key : map.keySet()) {
  System.out.println("Key : " + key.toString() + " Value : "
   + map.get(key));
 }
 
  }
 
}

Monday, 19 November 2012

Scrollable Window using Swing

Example Links

http://docs.oracle.com/javase/tutorial/uiswing/examples/components/index.html#ScrollDemo

Eclipse


Releases

Since 2006, the Eclipse Foundation has coordinated an annual Simultaneous Release. Each release includes the Eclipse Platform as well as a number of other Eclipse projects. Until the Galileo release, releases were named after the moons of the solar system.
So far, each Simultaneous Release has occurred at the end of June.
Release         Date             Platform version    Projects
Indigo          June 2011        3.7                 Indigo projects
Helios          23 June 2010     3.6                 Helios projects
Galileo         24 June 2009     3.5                 Galileo projects
Ganymede        25 June 2008     3.4                 Ganymede projects
Europa          29 June 2007     3.3                 Europa projects
Callisto        30 June 2006     3.2                 Callisto projects
Eclipse 3.1     28 June 2005     3.1  
Eclipse 3.0     28 June 2004     3.0  
To summarize, Helios, Galileo, Ganymede, etc are just code names for versions of the Eclipse platform (personally, I'd prefer Eclipse to use traditional version numbers instead of code names, it would make things clearer and easier)

Sunday, 18 November 2012

Servlet

Servlet Link

First Example
http://met.guc.edu.eg/OnlineTutorials/JSP%20-%20Servlets/A%20servlet%20example.aspx

JSP


Transformation process from JSP file into Java byte code

JSP  -> translated -> Servlet Java File -> complied    -> Class File -> loaded into memory 


Servlets and JSPs

Although there are individual specifications for both Servlets and JavaServer Pages, the end result of both is a Servlet class loaded in memory; JSPs are translated from a JSP to a Servlet Java file, compiled to a class file, and finally loaded into memory. Servlets and JSPs do not maintain state between requests, so application servers pool them. So you can tune the pool size and the number of Servlets that are preloaded into the pools.
Because JSPs go through the translation and compilation step prior to being loaded into memory, most application servers provide a mechanism by which you can precompile your JSPs before you deploy them. This removes the delay that end-users would experience the first time a JSP is loaded.
Servlets (and JSPs) are required to maintain four different scopes, or areas of memory that data can be stored in:
  • Page: Data stored here exists for the context of a single page.
  • Request: Data stored here exists for the duration of a request (it is passed from Servlet to Servlet, JSP to JSP, until a response is sent back to the caller).
  • Session: Data stored here exists for the duration of a user's session (it exists through multiple requests until it is explicitly removed or it times out).
  • Application: Data stored here is global to all Servlets and JSPs in your application until it is explicitly removed or until the Servlet container is restarted.
As a programmer, the choice of where to store data is a very important one that will impact the overall memory footprint of your application. The greatest impact, however, is the session scope: The amount of data that you store in here is multiplied for each concurrent user. If you store 10 kilobytes of data in your session scope for each user and you have 500 users, the net impact is 5MB. 5MB might not kill your application, but consider all 500 users going away and 500 more come. If you do not "clean up" after the users that left, you now are using 10MB, and so on. HTTP is a stateless protocol, meaning that the client connects to the server, makes a request, the server responds, and the connection is terminated. The application server then cannot know when a user decides to leave its site and terminate the session. The mechanism that application servers employ, therefore, is a session timeout; this defines the amount of time that a session object will live without being accessed before it is reclaimed. The session timeout that you choose will be dependent on your application, your users, and the amount of memory you are willing to set aside to maintain these sessions. You do not want to interrupt a slow user and make him restart his transaction, but you do not want to drain your system resources with a timeout that is any longer than is necessary.

Sunday, 4 November 2012

Hibernate

Hibernate 



Composite key:
https://forum.hibernate.org/viewtopic.php?p=2306165&sid=857145b56a9e06c8fa10aca8199c7312

Interview question:
http://java-success.blogspot.in/2010/12/hibernate-interview-questions-q.html

Jar files required : 

antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
hibernate-commons-annotations-3.2.0.Final.jar
hibernate-core-3.6.7.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
javassist.jar
jms-1.1.jar
jsr250-api-1.0.jar
jta-1.1.jar
log4j-1.2.16.jar
ojdbc14.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
+
your specific driver jar file

Configuration files 
hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mysqltest</property>
<property name="hibernate.connection.username">root</property> 
<property name="hibernate.connection.password">mysql</property>   <!--  connection property -->

<property name="show_sql">true</property> <!--  echo sql statement on console -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!--  tells the hibernate which database using so that can generate adequate sql  -->
<property name="hibernate.hbm2ddl.auto">create</property> <!--  Automatically creates, updates, or drops database schema on startup and shut down There are three possible values: create, createdrop, and update Be careful with create-drop  -->
<property name="current_session_context_class">thread</property> <!-- Enable Hibernate's automatic session context management  This is mandatory when created session using Session session = new Configuration().configure().buildSessionFactory().getCurrentSession() -->
<!-- Mapping files -->
<mapping resource = "bookapp.hbm.xml"/>

</session-factory>
</hibernate-configuration>

bookapp.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.bookstore">

<class name="BookDetails" table="BookStore">

<id name="id" type="int" column="id"> <!--  this is must to define -->
<generator class="native"></generator>           <!--  native -> has to be generated by database -->
</id>

<property name="name" type="string" column="bname"/>
<property name="author" type="string" column="author"/>
<property name="cost" type="int" column="bcost"/>

</class>
</hibernate-mapping>


SessionFactory and Session 
The Session is used to create a new database object, read in objects from the database,
update the objects in the database, and delete objects from the database. It allows us to manage
the transaction boundaries of database access. 
If you are familiar with the connected approach, it helps to think of a Session as
being somewhat like a JDBC connection, and the SessionFactory, which provides Session
objects, as being somewhat like a ConnectionPool, which provides Connection objects. The
SessionFactory is an expensive object—needlessly duplicating it will cause problems quickly,
and creating a SessionFactory is a relatively time-consuming process. Ideally, you should have
a single SessionFactory for each database your application will access. The SessionFactory
is threadsafe, so it is not necessary to obtain one for each thread. However, you will create
numerous Session objects—at least one for each thread using Hibernate as the Session is not
threadsafe—and, often, you will want to create multiple Session instances even during the
lifetime of a specific thread.



Best practice always created SessionFactory once(example)
SessionFactory is once per application per database. Use a suitable singleton class to enforce
this. Sessions are once per thread. Use ThreadLocal variables to enforce this, or use the built-in
SessionFactory.getCurrentSession() method available in Hibernate 3.0.1 and higher.

package com.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
public static final SessionFactory SESSION_FACTORY;
static{
try{
SESSION_FACTORY = new Configuration().configure().buildSessionFactory();
}catch (Throwable e) {
System.err.println("Initial session factory creation failed " + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getFactory(){
return SESSION_FACTORY;
}
}


How to create Session

Scenario1
Session session =  HibernateUtil.getFactory().getCurrentSession();
session.beginTransaction();
_ _ _ 
session.getTransaction.commit();
session.close(); 
// for above scenario we need to configure thread in hibernate.cfg.xml "Enable Hibernate's automatic session context management"

Scenario2


Session session = HibernateUtil.getFactory().openSession();
Transaction tx = null;
try{
tx = session.getTransaction();
tx.begin();
_ _ _ _ 
       tx.commit();
       tx = null;
} catch (HibernateException e) {
      if (tx != null) tx.rollback();
} finally {
session.close();
}

// for above scenario no need to configure current_session_context_class

Example



public void addBook(String bookName, String authorName, int bookCost){

//using persistent object to store data in database 


// Session session =  HibernateUtil.getFactory().getCurrentSession();
// session.beginTransaction();
//
// BookDetails bd = new BookDetails();
// bd.setName(bookName);
// bd.setAuthor(authorName);
// bd.setCost(bookCost);
//
// session.save(bd);
// session.getTransaction().commit();



Session session = HibernateUtil.getFactory().openSession();
Transaction tx = null;
try{
tx = session.getTransaction();
tx.begin();

BookDetails bd = new BookDetails();
bd.setName(bookName);
bd.setAuthor(authorName);
bd.setCost(bookCost);

session.save(bd);
tx.commit();
tx = null;
} catch (HibernateException e) {
if (tx != null) tx.rollback();
} finally {
session.close();
}







Querying with HQL and SQL


Although you should probably use HQL wherever possible, Hibernate does provide a way to
use native SQL statements directly through Hibernate. One reason to use native SQL is that
your database supports some special features through its dialect of SQL that is not supported
in HQL. Another reason is that you would like to call stored procedures from your Hibernate
application.



Example for HQL and SQL 

public void countBook(){
Session session =  HibernateUtil.getFactory().getCurrentSession();
session.beginTransaction();

//using aggregate functIon 
List list = session.createQuery("select count(*) from BookDetails").list();            // here using Java class name 
System.out.println("Using Agg function " + list);
//using native sql 
List list1 = session.createSQLQuery("select count(*) as count from BookStore").addScalar("count",Hibernate.INTEGER).list();
System.out.println("Usin native " + list);
session.getTransaction().commit();
}


public void listBook(){


//NatIve sql query
Session session =  HibernateUtil.getFactory().getCurrentSession();
session.beginTransaction();

List list = session.createSQLQuery("select * from BookStore").addEntity(BookDetails.class).list();   // here using database table name 
Iterator<BookDetails> Item = list.iterator();
while(Item.hasNext()){
System.out.println(Item.next());
}

session.getTransaction().commit();

}


public SQLQuery createSQLQuery(String queryString) throws HibernateException
After you pass a string containing the SQL query to the createSQLQuery() method, you
should associate the SQL result with an existing Hibernate entity, a join, or a scalar result. The
SQLQuery interface has addEntity(), addJoin(), and addScalar() methods. For the entities and
joins, you can specify a lock mode, which we discuss in Chapter 9. The addEntity() methods take
an alias argument and either a class name or an entity name. The addJoin() methods take an
alias argument and a path to join.