Thursday, December 24, 2009

Java’s String pooling


A string pool is a collection of references to String objects.
Strings, even though they are immutable, are still objects like any other in Java. Objects are created on theheap and Strings are no exception.
So, Strings that are part of the "String Literal Pool" still live on the heap, but they have references to them from the String Literal Pool.

When a .java file is compiled into a .class file, any String literals are noted in a special way, just as all constants are. When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals. When it finds one,  it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the constant table. Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Literal Pool.
If you use the new keyword, a new String object will be created. Note that objects are always on the heap - the string pool is not a separate memory area that is separate from the heap.
The string pool is like a cache. If you do this:
String s = "abc";
String p = "abc";
then the Java compiler is smart enough to make just one String object, and s and p will both be referring to that same String object. If you do this:
String s = new String("abc");
then there will be one String object in the pool, the one that represents the literal "abc", and there will be a separate String object, not in the pool, that contains a copy of the content of the pooled object. Since String is immutable in Java, you're not gaining anything by doing this; calling new String("literal") never makes sense in Java and is unnecessarily inefficient.
Note that you can call intern() on a String object. This will put the String object in the pool if it is not already there, and return the reference to the pooled string. (If it was already in the pool, it just returns a reference to the object that was already there). See the API documentation for that method for more info.
Java String intern Function
public String intern() 
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.


Tuesday, December 22, 2009

Inversion of Control ( IOC ) Design pattern

Inversion of Control (IoC) design pattern  Basics
The Inversion of Control (IoC) pattern is also known as Dependency Injection.
The basic concept of the Inversion of Control pattern is that programmers don’t need to create the objects but describe how they should be created.
IOC  design pattern  alleviates  application objects from the responsibility of creating, and managing their dependencies. Instead, these application objects are free to concentrate solely on fulfilling their business purpose .

Types of IoC
     Interface Injection (Type 1)
     Setter Injection (Type 2)
     Constructor Injection (Type 3)

Some frameworks implementing IOC


For more detailed Information on IOC 

Friday, November 27, 2009

Servlet Container & Request processing

Why we need Container for Servlets?

    Servlets don't have main() method,They run under
    control of another java application called container.
    Ex: Tomcat

When Server gets request for servlet the server handovers
the request to container in which Servlet is deployed.

In simple "Container manages and runs the Servlet".

Advantages of using Container:

Communication
The container provides easy way of communication between servlets and web server.

Life-cycle Management:
The container controls the life cycle of servlet.
    Loading classes.
    Instantiating and initializing the servlet.
    Invoking servet methods ie  like init service & destroy .
    Destroying servlets for garbage collection ( Resource management ).

Threading support:
Container automatically creates a new java thread for every
request it receives.The thread dies when servlet completes
running the HTTP service method.
  
Security:   
    Container provides XML based configuration for security configuration and
modification of servlet with out changing the java code of servlet.
  
JSP support:
    Container takes care of converting JSP code into java.      

Handling the request:

When user request for Dynamic content
1)Container gets request  for servlet.
2)Container creates HTTPServletResponse and HTTPResponse objects.
3)Based on the requested URL Container maps the request to a  sevlet
and creates a thread for the request  and  passes the references of
HTTPServletResponse and HTTPResponse objects.
4)Container calls the service(),Which in-turn calls the doXXX()
methods based on the request type.
5)the doXXX() method constructs the dynamic page into HTTPResponse object.
6)When response is sent to client container deletes the objects and thread.

Thursday, November 19, 2009

Creating jasper reports in 4 simple steps


Download the jasper reports Lib and Source from here.
Intro:

    JasperReports is an open-source Java class library
    designed to aid developers with the task of adding
    reporting capabilities to Java applications.
    JasperReports is licensed under the Lesser GNU Public License (LGPL).
Features:
    It has flexible report layout.
    It is capable of presenting data textually or graphically.
    It allows developers to supply data in multiple ways.
    It can accept data from multiple datasources.
    It can generate watermarks.
    It can generate subreports.
    It is capable of exporting reports to a variety of formats.
Flow chart of Jasper Reports Creation
    We can Create Jasper report in Following four steps.


Create JRXML files:
    The first step is to create a report template
    as an XML file.Even though JasperReports'
    report templates are XML files,template filenames
    are given an extension of .jrxml.
    JasperReports XML templates are commonly referred to as JRXML files
Compile JRXML files to create Jasper File :
    JRXML files are compiled into a JasperReports
    native binary template.The resulting compiled
    template is commonly known as the Jasper
    file, and is typically saved to disk with a .jasper extension.
Fill The report:
    The Jasper file is then used to generate the final report,
    by providing it with its required data.
    This process is known as filling the report.
Display the report:
    Filled reports can be saved to disk in a JasperReports 

    native format. Reports saved in this format are known
    as JasperPrint files.
    JasperPrint file names have a .jrprint extension.
    JasperPrint files can be exported to other
    formats so that they can be opened with commonly
    available tools like PDF viewers and word processors.

Wednesday, November 11, 2009

MySQL monitoring Using ' mycheckpoint '

Download the packge from here .
Dependencies
    yum install MySQL-python.
Installation   
  untar the file and run follwoing commands
          tar xzfv mycheckpoint-XXX.tar.gz
          cd mycheckpoint-XXX
          sudo python setup.py install


Run follwing commads on mysql prompt
     CREATE DATABASE mycheckpoint;   
     GRANT ALL PRIVILEGES ON mycheckpoint.* TO                        
                     'monitoring_user'@'localhost' IDENTIFIED BY '_password';
    GRANT SUPER ON *.* TO 'monitoring_user'@'localhost';
    GRANT REPLICATION CLIENT ON *.* TO 'monitoring_user'@'localhost';


Run following command on command prompt
  
           mycheckpoint --user=monitoring_user --password=_password
           --host=localhost --socket=/tmp/mysql.sock -v --chart-width=500
           --chart-height=300 deploy


Creating defaults-file:

[client]
user=monitoring_user
password=_password
socket=/tmp/mysql.sock
port=3306
host=localhost
Create a file with above contents and save it as /root/.my-checkpoint.cnf
make follwing crontab entry

      */5 * * * *     mycheckpoint --defaults-file=/root/.my-checkpoint.cnf

Detecting parameters change:
   
    SELECT * FROM sv_param_change;
   
Generating Google charts:
    DESC sv_report_chart_sample;

    SELECT DML FROM sv_report_chart_hour \G
     we can create google charts for all the values in sv_report_chart_sample.

Generating HTML reports:

        mysql --user=monitoring_user --password=_password
                   --host=localhost   mycheckpoint 
                    -e "SELECT html FROM sv_report_html" --silent --raw >
                       /tmp/mycheckpoint_report.htm
l

Generating human Readable reports:

Previous hour’s report by:

    SELECT report FROM sv_report_human_hour ORDER BY id DESC LIMIT 1,1 \G

Last week’s report by:

    SELECT report FROM sv_report_human_day WHERE ts = DATE(NOW()) - INTERVAL 7 DAY\G

And all 24 of yesterday’s hourly reports by:

    SELECT report FROM sv_report_human_hour WHERE ts >= DATE(NOW()) - INTERVAL 1 DAY AND ts < DATE(NOW())\G
   
Replication Monitoring:
   
    SELECT seconds_behind_master FROM sv_report_chart_hour\G

Estimating slave catchup time   

    SELECT ts, estimated_slave_catchup_seconds FROM sv_report_hour;

Wednesday, October 28, 2009

SED Delimiters and usage

Delimiters in SED substitute command  @ % | ; :
The follwing two commands are same.

    sed 's@/home/@/myhome@g' saple.txt
    sed 's/\/home\//\/myhome\//g' saple.txt


The part of an input line on which the Regular Expression matches is represented by & ,
and It can be used in the replacement part.

      sed 's/input/&output/g'
      output: inputoutput


Grouping can be used in sed like normal regular expression.

    A group is opened with “\(” and closed with “\)”.
     sed 's@\(myhome\).*@\1@g'

Parenthesize first character of each word

 echo "Welcome To The Geek Stuff" | sed 's/\(\b[A-Z]\)/\(\1\)/g'

 
Source and More Info
 
 

Tuesday, September 29, 2009

Increasing open files limit on Linux

Q) How to check open files limit on Linux ?
A) ulimit -a

ulimit Provides control over the resources available to the shell and to processes started by it, on systems that allow such control.
-a All current limits are reported


[testuser@localhost /]$ ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 16303
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 10240
cpu time (seconds, -t) unlimited
max user processes (-u) 1024
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited


Q) How to increase open files limit ?
A) Add the following entries in /etc/security/limits.conf

* soft nofile 8192
* hard nofile 8192

Default limit is 1024 ,You can Increase the limit based on requirement.
In this example I am increasing limit to 8192.

Note that you may need to log out and back in again before the changes take effect.

[testuser@localhost ~]$ ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 16303
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 8192
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 10240
cpu time (seconds, -t) unlimited
max user processes (-u) 1024
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited


You can check only open files limit using 'ulimit -n'.