Thursday, May 26, 2011

Log4j - Email errors using Gmail

Most of the small projects doesn't have a dedicated person to monitor log file all the times, and its handy to send these errors as email to an email list.

Pros


  1. Never miss an error.
  2. Delete Emails which you want to ignore because of invalid inputs or connectivity issues etc.
  3. Proactively identify bugs and fix them.
  4. Email list is handy i.e. multiple person can receive emails.
  5. If you have different modules in your project and different teams work on them, adding a Labels to your log can by handy since most of the Email Servers can Label emails and redirect them to different folders.
Cons
  1.    Sending email from code takes few seconds, workaround is the create Logger wrapper which logs in a separate thread.

log4j.properties

log4j.rootLogger=ERROR, gmail
log4j.appender.gmail=org.apache.log4j.net.SMTPAppender
log4j.appender.gmail.SMTPProtocol=smtps
log4j.appender.gmail.SMTPPassword=password
log4j.appender.gmail.SMTPHost=smtp.gmail.com
log4j.appender.gmail.SMTPPort=465
log4j.appender.gmail.Subject=Some subject line
log4j.appender.gmail.layout=org.apache.log4j.PatternLayout
log4j.appender.gmail.layout.ConversionPattern=%d{MM/dd/yyyy HH:mm:ss}  [%M] %-5p %C - %m%n
log4j.appender.gmail.BufferSize=10


Required Jar files

Activation  download from here

Sample Code

public class Log4jGmailDemo {

    public static void main(String[] args) {
        try {
            int z = 4 / 0;
        } catch (RuntimeException re) {
            logger.error("Module-1", re);
        }
    }
    static Logger logger = Logger.getLogger(Log4jGmailDemo.class);
}

This is only if you are interested using Threads 


public class CustomLogger extends Logger {

    public CustomLogger(String clazz) {
        super(clazz);
    }

    @Override
    public void error(Object message) {
        Runnable runnable = new LoggerRunnable(this, message, null);
        LogExecutor.getInstance().execute(runnable);
    }

    @Override
    public void error(Object message, Throwable throwable) {
        Runnable runnable = new LoggerRunnable(this, message, throwable);
        LogExecutor.getInstance().execute(runnable);
    }

    public static Logger getLogger(Class clazz) {
        return new CustomLogger(clazz.getSimpleName());
    }
}

class LogExecutor {

    private static LogExecutor executor = new LogExecutor();

    private LogExecutor() {
    }
    private ExecutorService service = Executors.newFixedThreadPool(5);

    public static LogExecutor getInstance() {
        return executor;
    }

    public void execute(Runnable runnable) {
        service.execute(runnable);
    }
}

class LoggerRunnable implements Runnable {

    private Logger logger;
    private Object message;
    private Throwable throwable;

    public LoggerRunnable(Logger logger, Object message, Throwable throwable) {
        this.logger = logger;
        this.message = message;
        this.throwable = throwable;
    }

    @Override
    public void run() {
        logger.error(message, throwable);
    }
}

Sample Usage



public class Log4jGmailDemo {

    public static void main(String[] args) {
        try {
            int z = 4 / 0;
        } catch (RuntimeException re) {
            logger.error("Module-1", re);
        }
    }
    static Logger logger = CustomLogger.getLogger(Log4jGmailDemo.class);
}
 
 
PS: you can use AsyncAppender to make non-blocking emailing of logs instead of writing your own.

Monday, May 23, 2011

Inner Classes in Java

There are 4 kind of classes that can be defined in a Java program, roughly can be termed as the inner classes.

--  Inner classes provides an elegant and powerful feature to the Java programming language. 
-- These inner classes are referred by different names in different situations. 

-- They are summarized here:
  1.
Static member classes
  2. Member classes
  3. Local classes
  4. Anonymous classes

-- The term "nested classes" sometimes refers to these inner classes.

Static member classes

  --
This class (or interface) is defined as a static member variable of another class.
Member classes
--  This is sometimes defined as a non-static member of an enclosing class. This type of inner class is analogous to an instance method or field.
Local classes
-- This class is defined within a block of Java code so like a local variable, it is visible only within that block.
Anonymous classes
-- An anonymous class is a  local class having no name; -- Syntactically it combines the syntax required for defining a class and the syntax required to instantiate an object.
 The below is an added little more explanation to the above.


When a class is defined within another class then such a class is called a nested class.
Inner class is a non static class declared inside another class.Non-static inner class keep the reference of outer class and allow to access member variable of outer class. It helps in defining an interface of a class.
We use nested classes because of the following reasons:
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation.Nested classes can lead to more readable and maintainable code.


Except the inner class, there are two types of supplementary  inner classes :
The inner class which is declared inside the body of a method is known as the local inner classes. The class declared inside the body of a method without naming it is known as anonymous inner classes.
Here we are discussing  anonymous inner classes.
The anonymous inner classes is very useful in some situation. For example consider a situation where you need to create the instance of an object without creating subclass of a class and also performing additional tasks such as method overloading.

Consider the following code :
button.addActionListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
// do something.
}
});
As you can see in the above code, i don't need to create an extra class that implements ActionListener . I initiated anonymous inner class(here it is new ActionListener()) without creating a separate class. You can also perform method overloading by implementing anonymous inner classes.

Software Quality with JAVA

Quality achievements in any software i.e. "quality of source code" it matters a lot to any project.
 
Software Quality depends on the factors like:
Testability: How easy it is to test. 
Maintainability
: flexibility to accommodate changes.


Every language must support a quality product whether it java, C# or any other language. 


However  The ISO 9126-1 identifies 6 main quality characteristics, that must are included in the software quality model namely:
  • Functionality
  • Reliability
  • Usability 
  • Efficiency 
  • Maintainability
  • Portability

Sunday, May 22, 2011

JBoss in Production


This a short topic on getting JBoss ready for the Production environment, I cover such things as selecting a platform, removing unnecessary services, securing the application services, etc
Selecting a platform can be a daunting task, although costs does play a major part, you also have to decide on what JVM you want to use as well which the O/S may give you limited options.

There are a number of different JVM vendors Sun, IBM and BEA being the top three, all three implement there JVMs differently so make sure you know the difference between them, I leave you to the web to find out. One thing you should remember is try not to tie your application in to one particular vendor thus if you have to move then it should not be a major problem.
The below table details the JBoss versions and what minimum supported JVM can be used
JBoss Version Minimum JVM version required J2EE/Java EE version supported
AS 3.0 JVM 1.3 J2EE 1.3
AS 4.0 JVM 1.4 J2EE 1.4
AS 4.2 JVM 1.5 J2EE 1.4/Java EE 5
AS 5.0 JVM 1.5 Java EE 5
Running Multiple Instances

When using multiple instances you use the "-c" option with the "run" script, you can also change the network bindings by editing the server/xxx/conf/bootstrap/bindings.xml file, thus you should be able to elimate port clashes. You can also use the "-b" option to bind to a particular network interface as well (default is 127.0.0.1). There is also a port assignment feature in the server/xxx/conf/bootstrap/bindings.xml file, there is a bean called PortsDefaultBindings that increment the port numbers to use it see below

jboss.service.binding.set option run -c myconfig -Djboss.service.binding.set=ports-01
use a particular interface run -c myconfig -b 192.168.0.1
You can shutdown instances by using the shutdown scripts (or CTRL-C in the window), you must use the JNDI port (default 1099) because it uses the MBeanServerConnection object.
shutting down instances shutdown -s 192.168.0.1:1099 -S
Unwanted Services
There are a number of services that you can disable if you do not require them
Service Delete these files/directories
Mail Service server/xxx/deploy/mail-service.xml

server/xxx/lib/mail*.jar
Scheduler Service server/xxx/deploy/scheduler-service.xml

server/xxx/deploy/schedule-manager-service.xml

server/xxx/lib/scheduler-plugin*.jar
Monitoring Service server/xxx/deploy/monitoring-service.xml

server/xxx/lib/jboss-monitoring.jar
Messaging (JMS) Service server/xxx/deploy/messaging

server/xxx/deploy/jms-ra.rar


server/xxx/lib/jboss-messaging*.jar
Unique ID key generator server/xxx/deploy/uuid-key-generator.sar

server/xxx/lib/autonumber-plugin.jar
HTTP Invoker service server/xxx/deploy/http-invoker.sar

server/all/deploy/httpha-invoker.sar
Home page server/xxx/deploy/ROOT.war
JMX Console server/xxx/deploy/jmx-console.war
Web Console server/xxx/deploy/management
Quartz scheduler service server/xxx/deploy/quartz-ra.rar
You can increase security by editing the server/xxx/conf/login-config.xml, take a look at the security topic for more details.
It might be an idea to change the default database which is the Hypersonic SQL database (HSQLDB) which is a in memory, pure Java database. You can use many of the free databases MySQL, PostgreSQL or a commercial one like Oracle, have a look at the deployment topic on how to set this up. There are a number of services that use the DefaultDS (default data source), so these will have to be updated to point to you new database
Service Configuration File
Login Modules server/xxx/conf/login-conf.xml
Container-Managed Persistence (EJB 2.x) server/xxx/conf/standardjbosscmp-jbdc.xml
Hypersonic Data Source server/xxx/deploy/hsqldb-ds.xml

common/lib/hsqldb*.jar
Timer Service (EJB 2.x) server/xxx/deploy/ejb2-timer-service.xml
Timer Service (EJB 3.x) server/xxx/deploy/ejb3-timer-service.xml
Schedule Manager Service server/xxx/deploy/schedule-manager-service.xml
Messaging Service server/xxx/deploy/messaging/hsqldb-persistence-service.xml

server/xxx/deploy/messaging/messaging-jboss-beans.xml
Universal Description, Discovery and Integration (UDDI) Service server/all/deploy/juddi-service.sar/juddi.war/WEB-INF/jboss-web.xml


server/all/deploy/juddi-service.sar/META-INF/jboss-service.xml
Simple Network Management Protocol (SMNP) Adaptor Service server/all/deploy/snmp-adaptor.sar/attributes.xml
Universally Unique ID (UUID) key generator Service server/xxx/deploy/uuid-key-generator.sar/META-INF/jboss-service.xml
The EJB3 timer service uses the Quartz job scheduler from Open Symphony, the default is to use the Hypersonic database but it can be used with any number of databases. The first thing is to download the Quartz source file that corresponds to the version provided by JBoss. You can get this information from the META-INF/Manifest.mf file located in common/lib/quartz.jar. You need to change two things
ejb3-timer-service.xml You need to change the delegate class to match the one from your database, valid delegates can be found in the src/java/org/quartz/impl/jdbcjobstore directory or the Quartz source.
ejb3-timer-service.xml The SqlProperties attribute contains a number of sql statements that need to be changed to match your database, these can be found in docs/dbTables in the Quartz source.
One note is that the JBoss 5.0.1.GA has now moved the file to the docs/examples/ejb3 directory
JSP Compilation
By default JBoss does not compile a JSP file until the first time it is accessed, after that it checks whether the underlying JSP has changed and recompiles if necessary. In a Production environment you generally release your changed code in a controlled manor, this means that you should turn off lazy JSP compiling feature. This feature is handled by the Java Servlet deployer and the file is located server/xxx/deployers/jbossweb.deployer/web.xml this is well documented within the file so you should have no problems in finding the location you need to change, the options are below
Parameter Description
development if true the frequency at which JSPs are checked for modification can be specified via the modificationTestInterval parameter, default is true
checkInterval If development is false and checkInterval is greater than 0, background compilations are enabled. checkInterval is the time in seconds between checks to see if a JSP needs to be recompiled, default is 0
modificationTestInterval Causes a JSP (and its dependent files) to not be checked for modification during the specified time interval (in seconds) from the last time the JSP was checked for modification. A value of 0 causes the JSP to be checked on every access, used in development mode only, default is 4


JBoss Installation


Before we start I would like to make one note and that is when you install software try and rename the installation directory (not to use any spaces) because in some environments (Windows) it likes to place JBoss in a pathname that has spaces (c:\program files\...), when you develop applications later, spaces in pathnames will cause you major headaches.
The first task we need to do is to obtain the JDK from Sun (http://java.sun.com), I used version 1.6.0 and JBoss runs perfectly but you might want to try with the latest version, download the JDK and install into your environment following Sun's instructions. Once installed don't forgot to set a JAVA_HOME environment variable that points to your JDK.

JAVA_HOME set JAVA_HOME=c:/jdk1.6.0_12
Installing JBoss is simple and there are a number of ways that you can install it
  • Binary
  • Using JEMS (GUI)
The fastest way to install JBoss is to download the binary version from http://www.jboss.org, unzip it and copy it to directory and that's it, it is ready to go, no installation. If you are going to install it straight into Production, then you need to make some changes to the default configuration to secure it, I have a topic on Production configurations. JBoss will work straight out of the box and is ideal for a development environment, the other route is to use JEMS installer which is a GUI based installer that allows you to configure the services that JBoss will use, you need to download the jems-installer file (http://labs.jboss.com/jeminstaller) which is an executable JAR file (90MB), looking at the web site the JEMS installer does not appear to supported very well as the link did not work but you can obtain the file from SourceForge.
It appears that the binary installation is the preferred way to go, one note is that there is no installation and everything that you need is contained in one directory (no registry settings or package stuff), this means you just copy the directory and put onto any server (Windows or Unix) and it should start up, the only difference is the way you start JBoss
  • Windows - run.bat
  • Unix - run.sh
There is a file called "service" in the bin directory which can create a windows JBoss service for you, I had problems when using this, it gave a file error message, this was because of the "jbosssvc" wrapper file was either corrupt or the wrong type, search for a newer version on the web and replace the one in the original install (I have a link below to the one I used)
create a windows JBoss service c:\jboss6\bin\service install
Note: downloaded jbosssvc file
Directory Structure
When you have finished installing JBoss you should have a top level directory structure like below (Yes. I know its JBoss 4 but its the same layout)


bin This directory contains all the scripts (both Unix and Windows) that you will need to start and stop JBoss. There are a number of others files here
  • twiddle - we discussed this earlier
  • probe - used to discover JBoss AS clusters
  • wsconsume - Used for web services
  • wsprovide - Used for web services
  • wsrunclient - Used for web services
  • wstools - Used for web services
  • run.sh and run.bat - used to start JBoss

client This directory contains many Java libraries that are used to communicate with JBoss server from a client application. These client applications are called standalone client or remote clients and could be Swing applications, remote Web services, JMS clients. If for what ever reason you need to use these libraries use the jbossall-client.jar file, this jar file contains a META-INF/Manifest.mf file that contains a class path reference to all the jar files in this directory.
common This directory I believe is from the version 4 JBoss implemention, where all common Java libraries were placed so that all web application could use them, I now believe that all common libraries should be placed in the <server config>/lib directory (see below).
docs There are no user manuals in this directory, but it contains the following

  • Document type definition (DTD) files and XML schemas for the configuration files that JBoss AS uses
  • Configuration examples for various J2EE and JBoss AS
  • Licenses for various libraries included in JBoss AS
  • Unit test results from the tests run against the server for the particular release


lib This directory contains all the libraries that need to start the core JBoss server. Do not put any libraries that you want to use across all web applications, these need to go in <server config>/lib (see below)
server This directory only has the server configurations in it, each directory represents a different server configuration that JBoss can be started in (see above).
Normally you copy a particular directory that suits you and rename to what ever you want and then configure this directory for your environment, then use the -c option to start your server configuration



c:\jboss5\bin\run.bat -c myServerConfig
The server directory holds the server configuration, see above for the layout of this directory
conf Each server configuration has a conf directory that holds files used for servlet-wide configuration. This directory is only scanned once during the boot sequence so any changes that yo make are not picked up until you restart the server. The import files in this directory are
  • bootstrap.xml - defines core microcontainer services
  • jboss-service.xml - defines core JMX services
  • jboss-log4j.xml - configures logging
  • login-config.xml - configures authentication and authorization modules for security
  • standardjboss.xml - used to configure the various EJB containers
  • jacorb.properties - Used to configure the Java Object Request Broker (JacORB) service, used in clustering
  • jax-ws-catalog.xml - Used to map XML metadata names to local metadata descriptor files
  • jbossjta-properties.xml - Used to configure the Java Transaction API (JTA) service
  • jboss-service.xml - a variation of the jboss-service.xml file configured for a minimal app server configuration
  • jndi.properties - Used by the JNDI service to define default properties
  • standardjbosscmp-jdbc.xml - Used by the EJB service to define type mappings for various databases for data persistence

deploy this is where applications and services are deployed. You can deploy any application packages here for example JAR, WAR or EAR that you create. By copying them into this directory JBoss will automatically deploy them to the application server.
deployers contains all the JBoss AS services that are used to recognize and deploy different applications and archive types, for example the ejb3.deployer directory contains libraries and configuration files necessary for starting the service that deploys EJB3 applications that you deploy into the deploy directory.
lib this directory holds all the Java libraries that can be accessed by all web applications.
Generated Directories JBoss creates additional directories when first started
  • data - used to write to the filesystem for storing temporary data
  • log - holds three log files: boot.log, server.log, audit.log
  • tmp - stores temporary data by various services
  • work - used by the web server to store compiled JSP files and other temporary data
Server Configurations
JBoss is designed to be modular, this means that you add or remove services very easily, by removing unwanted services you can decrease the memory allocation and increase performance, it also reduces security risks. The picture below shows how the microcontainer runs on top of the JVM and how various application-server services plug into the microcontainer. When you start JBoss you are always starting a server configuration which is a directory structure under the server's server directory, it contains code, libraries and configuration files for a set of services and applications that run when the server starts.


Typically you copy one of the already supplied configurations and adapt it to your environment, then start this configuration using the -c option with run.bat or run.sh, or you can just use one of the supplied configurations.
start a different configuration run.bat -c minimal




run.bat -c <your configuration>
Pre-Configurations
all Includes everything - clustering, RMI/IIOP support
default this is the default configuration if you do not specify anything, it does not include a web container, no ejb or JMS support
minimal Includes only JNDI, logging services an a URL deployment scanner to find new deployments
standard
web Used to contain services which will allow simple web applications (servlet, jsp) to be deployed.
JBoss Boot Sequence
I have read a number of JBoss books and none of them detailed the JBoss boot sequence, searching the web and using the JBoss log file, I will put a quick summary of the boot sequence below, it may not be to accurate but there is no document that explains this well, I will update this as and when I get more information.

  • You start JBoss by running the run.bat or run.sh script, this script sets some variables and then initiates the boot sequence using the org.jboss.Main.main method entry point.
  • The main method creates a thread group then starts the microcontainer org.jboss.bootstrap.microcontainer.ServerImpl
  • The microcontainer opens the bootstrap.xml, which is a file that contains various MBeans descriptors that should be loaded by the BasicXMLDeployer
  • Once the MainDeployer has been invoked it uses the conf/jboss-service.conf file to start the services required for the web application
bootstrap.xml Defines the core microcontainer services that start when the server first starts.
bootstrap.xml file
vfs.xml This configures the Virtual filesystem, which is a simple read-only framework abstracting the way we look at the the filesystem. It uses virtual files which can be accessed by a URI/URL (uses a URI/URL:MBean link pairing)
classloader.xml This configures the core classloading system and classpath
aop.xml Aspect-oriented programming is a programming paradigm that increases modularity by allowing the separation of cross-cutting concerns. (its a post OOP programming paradigm)
jmx.xml This configures the JMX Kernel Mbeans
deployers.xml This configures the MainDeployer, Structure Deployers, the bootstrap MC and the JMX deployer
binding.xml This configures the ServiceBindingManager bean and configuration
profile-repository.xml This configures the ProfileService beans which includes management and deployment support.
Starting and Stopping JBoss
To start JBoss using the default configuration, you open a console window and go to the bin directory, then run "run.sh" or "run.bat", you can also use the -c option to change the default server configuration, I have already discussed this above. To stop JBoss use the "shutdown" command

Starting JBoss # cd <JBoss dir>/bin



# run.sh

c:\> run.bat





# run.sh -c all
Stopping JBoss # shutdown.sh

c:\> shutdown.bat
When JBoss has started you should see the below line in the log file, you can also check that JBoss has started by using the following URL http://localhost:8080
JBoss has started 2009-04-03 12:05:12,125 INFO [org.jboss.bootstrap.microcontainer.ServerImpl] (main) JBoss (Microcontainer) [5.0.1.GA (build: SVNTag=JBoss_5_0_1_GA date=200902231221)] Started in 1m:907ms

Logging
JBoss uses log4j an open source logging framework, the configuration file is located at server/xxx/conf/jboss-log4j.xml. I have already discussed log4j in my Tomcat tutorial, so have a look there first then continue back here. JBoss be default has two appenders configured, one for the console and for the server/xxx/log/server.log file. Most configuration setups use a rolling log file, it is created each time JBoss is stopped and restarted and at midnight it is rolled over, you can also specify a size for it to rollover.
Rolling logfile <log4j: ...>

  <appender name="FILE" class="org.jboss.logging.appender.RollingFileAppender">

    <errorHandler ../>

    <param name="File" value="${jboss.server.log.dir}/server.log"/>


    <param name="Append" value="true"/>

    <param name="MaxFileSize" value="10MB"/>

    <param name="MaxBackupIndex" value="20"/>


    <layout ../>

  </appender>

  ...

</log4j>
Limiting logging <log4j:...>

  ...

  <category name="org.jboss.jms">

    <priority value="WARN"/>


  </category>

</log4j>
System Properties
There are a number of system properties that define default directory locations
jboss.home.dir c:\jboss-5.0.0.GA

/opt/jboss-5.0.0.GA
jboss.home.url file:/c:\jboss-5.0.0.GA


file://opt/jboss-5.0.0.GA
jboss.lib.url <jboss.home.url>lib/
jboss.patch.url -none-
jboss.server.base.dir <jboss.home.dir>/server
jboss.server.base.url <jboss.home.url>server/
jboss.server.home.dir <jboss.server.base.dir>/default
jboss.server.home.url <jboss.server.base.url>default/
jboss.server.config.url <jboss.server.home.url>conf/
jboss.server.data.dir <jboss.server.home.dir>/data
jboss.server.lib.url <jboss.server.home.url>lib/
jboss.server.log.dir <jboss.server.home.dir>/log
jboss.server.temp.dir <jboss.server.home.dir>/tmp
You can also provide system properties on the commandline by using the "-D" option
supplying commandline properties c:\> run.bat -Djboss.server.log.dir=d:/log
There are two more systems properties which are of interest
jboss.server.name default
jboss.bind.address 127.0.0.1
System properties are used in a number of configuration XML files and as stated above you can add your own properties using the "-D" option
Using your own system properties c:\> run.bat -Dtrading.database.login=trader1 -Dtrading.database.password=traderpw
// In your oracle-ds.xml file
<user-name>${trading.database.login}</user-name>

<password>${trading.database.password}</password>



Sunday, May 15, 2011

MLAs & MPs who attended Jagan fasting centre .. !




Yuvajana Sramika Rythu Congress (YSR Congress) party President Jagan Mohan Reddy sits on 48-hour fasting at YSR Pranganam in Guntur. Thousands of farmers from across Andhra Pradesh joined agitation and expressed solidarity. Following leaders participated in Jagan Deeksha.




Leaders who participated in Jagan’s Rythu Deeksha:


 
S.No
Leader Name
Constituency
Distirct
MPs:
1.
Nellore MP
Nellore
2.
MLAs:
1.
M. Sucharitha
Prathipadu (SC)
Guntur
2.
P. Ramakrishna Reddy
Macherla
Guntur
3.
Ongole
Prakasam
4.
Darsi
Prakasam
5.
N. Prasanna Kumar Reddy
Kovur
Nellore
6.
G. Srikanth Reddy
Rayachoti
Kadapa
7.
Konda Surekha
Parkal
Warangal
8.
Nallamilli Seshareddy
Anaparthi
East Godavari
9.
Krishna Das
East Godavari
10.
Bharathi
Tekkali
MLCs:
1.
Pulla Padmavathi
Warangal
2.
Jupudi Prabhakar Rao
Prakasam
3.
Tippereddy
Chittoor
4.
Konda Murali
Parkal
Warangal
5.
Ex-MLAs:
1.
Makineni Pedaratthaiah
Ponnur
Guntur
2.
Marri Rajasekhar
Chilakaluripet
Guntur
3.
Ambati Rambabu
Tenali
Guntur
4.
Gudibandi Venkat Reddy
Tenali
Guntur
5.
Janga Krishnamurthy
Gurajala
Guntur
6.
Dr. Ravi Ravindranath Chowdary
Tenali
Guntur
7.
Ravi Venkataramana
Prathipadu
Guntur
8.
Bhooma Nagireddy
Allagadda
Kurnool
9.
J. Ramesh Babu
Mylavaram
Krishna
10.
Other Leaders:
1.
Bhoomana Karunakar Reddy
Tirupati
Chittoor
2.
Chevireddy Bhaskar Reddy
Chandragiri
Chittoor
3.
Gautam Reddy
Vijayawada
Krishna
4.
Alla Ramakrishna Reddy
Pedakurapadu
Guntur
5.
6.
7.
5.
6.
7.
Meruga Nagarjuna
Vemur
Guntur
5.
Shaik Yashin
Ponnur
Guntur
6.
7.

Tuesday, May 10, 2011

Why are the keys of a Map in a jumbled order

Overview

When you first try to printout a HashMap, the order doesn't make any sense and when you add entries, they appear to jump around. What is going on?

The order of Maps

The order keys should appear is not defined in many implementations.

Hash map uses a hash of the key to place the key/value in a pseudo random place in the underlying store (an array) How it does this is different in different implementations. For HashMap the size of the Map is always a power of 2. For Hashtable the size grows 11, 23, 47, 95.

For LinkedHashMap, the order will be the order the keys were added and for TreeMap & ConcurrentSkipList, the order is based of the Comparable.compareTo() result (asciibetical order for String)

For Hashtable and HashMap changing the initial size changes how the keys are hashed and thus their order

public static void main(String... args) {
    populate(new Hashtable());
    populate(new Hashtable(47), " (47)");
    populate(new Hashtable(95), " (95)");
    populate(new HashMap());
    populate(new HashMap(32), " (32)");
    populate(new HashMap(64), " (64)");
    populate(new LinkedHashMap());
    populate(new IdentityHashMap());
    populate(new WeakHashMap());
    populate(new ConcurrentHashMap());
    populate(new TreeMap());
    populate(new ConcurrentSkipListMap());
}

private static void populate(Map map) {
    populate(map, "");
}

private static void populate(Map map, String suffix) {
    for (String s : "one,two,three,four,five,six,seven,eight,nine,ten".split(","))
        map.put(s, s);
    System.out.println(map.getClass().getSimpleName() + suffix + " " + map.keySet());
}

prints

Hashtable [three, six, ten, seven, nine, one, five, four, two, eight]
Hashtable (47) [ten, five, seven, two, three, one, nine, six, eight, four]
Hashtable (95) [nine, five, six, one, seven, eight, ten, two, four, three]
HashMap [ten, two, seven, five, nine, one, three, four, eight, six]
HashMap (32) [ten, five, nine, one, eight, six, two, seven, three, four]
HashMap (64) [ten, nine, one, eight, six, three, four, five, two, seven]
LinkedHashMap [one, two, three, four, five, six, seven, eight, nine, ten]
IdentityHashMap [four, two, five, nine, three, six, eight, one, seven, ten]
WeakHashMap [six, eight, four, three, nine, one, seven, five, ten, two]
ConcurrentHashMap [seven, two, one, nine, four, six, eight, three, ten, five]
TreeMap [eight, five, four, nine, one, seven, six, ten, three, two]
ConcurrentSkipListMap [eight, five, four, nine, one, seven, six, ten, three, two]

Incorrect Core Java Interview Answers !!

Overview

On the Internet, Java interview questions and answers get copied from one web site to another. This can mean that an incorrect or out of date answer might never be corrected. Here are some questions and answer which are not quite correct or are now out of date. i.e. are pre Java 5.0.

How many ways can an argument be passed to a subroutine and explain them?

An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.
Java only supports Pass-By-Value. You can pass a reference by value, but you cannot pass by reference in Java. Java references can be described as Call By Sharing but this is not commonly used.

What is Garbage Collection and how to call it explicitly?

When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.
An object is eligible for cleanup when it no longer has a strong reference from a Root context. An object which has a weak or soft reference can be cleaned up. An object without a strong reference might not be cleaned up (i.e. there is no guarentee a GC will be run and a minor GC will not clean up tenured objects)

System.gc() is a hint that a Full GC should be run. This can be disabled using a command line option.

What are Transient and Volatile Modifiers?

Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.
transient can only be applied to fields and cannot be applied to local variables. It can be applied to static variables but will be generally ignored. Transient fields are not serialized automatically, but can be serialized by custom serialization e.g. writeObject and readObject()

volatile can only be applied to fields and the tell the JIT rather than the compiler that every access must get a cache coherent copy of the field. (Notionally from "main" memory)

Explain the usage of the keyword transient?

This keyword indicates that the value of this member variable does not have to be serialized with the object. When the class will be de-serialized, this variable will be initialized with a default value of its data type (i.e. zero for integers).
This keyword means the field cannot be serialized automatically. It is not de-serialized automatically leaving the default value for the field. The default for Integer is null. The default for int is 0


What is method overloading and method overriding?

Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.
Method overloading occurs when two methods have the same name but different signatures. The signature includes the parameter types and generic type. A single method can be called with different arguments and two overloaded methods can be called with the same arguments. i.e. its the signature not the arguments which matter.

Method overriding only occurs when a sub-class has the same signature as a method in a parent class.

It is worth clarifying that the return type is not part of the signature in Java. At the JVM level it is and covariant return types are implemented with generated method.

What is the difference between Integer and int

a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.
An Integer is a reference to an object which wraps an int The key difference since autoboxing and unboxing was added is that an Integer can be null and the == operator compares references for Integer and the actual values for an int type.
Integer i1 = 1;
Integer i2 = 1;
// true as the same autoboxed Integer is used.
System.out.println(i1 == i2); 

Integer i3 = -200;
Integer i4 = -200;
// false as different autoboxed Integer objects are used.
System.out.println(i3 == i4);

i3 == i4 is false as new Integer(int) is called by Integer.valueOf(int) which does the autoboxing.

Note: On the Sun/Oracle JVM the maximum value of integer cached defaults to 127, however it can be increased with the -XX:AutoBoxCacheMax= or -Djava.lang.Integer.IntegerCache.high= options. Thank you @Pedro Kowalski.

What are the different states of a thread ?

The different thread states are ready, running, waiting and dead.
Since Java 5.0, which should be most Java systems under development, the Thread.State class lists the threads possible states as
NEW
A thread that has not yet started is in this state.

RUNNABLE
A thread executing in the Java virtual machine is in this state.

BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.

WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.

TERMINATED
A thread that has exited is in this state.

Which is the base class for all classes?

java.lang.Object
This is true for custom classes. For primitive types such as int.class, void.class and Object itself have no super class.
Class parent = boolean.class.getSuperclass(); // returns null

What is daemon thread?


Theards [sic] which are running on the background are called deamon threads. daemon thread is a thread which doesn't give any chance to run other threads once it enters into the run state it doesn't give any chance to run other threads.
A Daemon thread is any thread which will not prevent the JVM from shutting down. Any thread can be considered a "background" thread. Daemon threads are given the same priority as non-Daemon threads (based on their priority) When a daemon thread is running it doesn't prevent another thread from running any differently from a non-daemon thread running.

Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system.

The garbage collector is an example of a daemon thread. A daemon thread can have a high priority and it can run all the time.

What are the restrictions placed on the values of each case of a switch statement?

At compile time, each case values of switch statement must evaluate to a an int value
From Java 5.0, switching on an enum is supported and from Java 7, switching on a String is supported.

What is a Java Bean?

A Java Bean is a software component that has been designed to be reusable in a variety of different environments.
IMHO: This answer is vague and could be talking about anything.

A Java Bean is a "Java Object that is serializable, has a nullary constructor, and allows access to properties using getter and setter methods."

Why would you use a synchronized block vs. synchronized method?

Synchronized blocks place locks for shorter periods than synchronized methods.
This can be true but is not guaranteed. Often synchronized blocks are used to hold a lock over multiple calls to an object with synchronized methods. IMHO the most common use for synchronized blocks is locking on another object other than this
Map<Key, Value> map = Collections.synchronizedMap(new LinkedHashMap<Key, Value>());
// perform multiple operations in a thread safe manner
synchronized(map) {
    Value value = map.get(key);
    if (value == null)
        map.put(key, value = new Value(key));
    return value;
}

Which one is faster in Java ?

for(int i = 100000; i > 0; i--) {}
for(int i = 1; i < 100001; i++) {}


Answer: Which ever is run second with be fastest. The server JVM can detect and eliminate loops which don't do anything. A method with either loop is compiled when the loop iterates about 10,000 times. (Based on -XX:CompileThreshold=10000) The first loop will take time to detect it doesn't do anything, however the second will have been compiled.

Which Java operator is right associative?

The = operator is right associative.
According to http://introcs.cs.princeton.edu/java/11precedence/ the list of right to left associative operators are. (A lot more than one)
  • ( ) cast
  • new Object
  • ? :
  • assignment   =   +=   -=  *=   /=   %=   &=   ^=   |= <<=   >>=   >>>=

What class of exceptions are generated by the Java run-time system?

The Java runtime system generates RuntimeException and Error exceptions.
IMHO: This an answer to a different question. This is an answer to; what are the super classes of runtime, unchecked exceptions?

The Java runtime can generate an Error, Exception or RuntimeException.

Links to this page

http://news.ycombinator.com/item?id=2789570http://news.ycombinator.com/item?id=2793399
http://www.javacodegeeks.com/2011/07/incorrect-core-java-interview-answers.html
http://java.dzone.com/articles/incorrect-core-java-interview
http://www.dzone.com/links/15_incorrect_yet_popular_core_java_interview_answ.html?ref=ps
http://news.ycombinator.com/item?id=2789570http://www.softwareservices.com/news/15833/incorrect-core-java-interview-answers/
http://www.dzone.com/links/rss/incorrect_core_java_interview_answers.html

Thursday, May 5, 2011

Checked Exceptions-3

I found a bug last week that was caused by a checked exception anti-pattern or maybe code smell. I name this smell "foo() throws Exception". The premise is that a method throws Exception, Throwable or any other exception which is low enough down in the class tree to capture the exceptions which may be thrown by the code that is being worked on. The software engineer happily beavers away without realising that the code is throwing all kinds of exceptions that are not being handled correctly. The handler is higher up the method chain and detached from what the code is actually doing so cannot reliably act, most likely it is simply logging exceptions. Once handled and logged nothing more is done possibly leaving the thread and/or application in an invalid state.

This can be caused by the programmer wanting the exception handling to go away perhaps because exceptions were used too liberally and now there is more exception handling than business logic. Maybe handling the exception is too uncomfortable since there is no plan B, there is only failure, but the application is long running and cannot be restarted so a catch-all was a last resort for an error that supposedly could not happen.

The application in question simulates a GSM-R application and calls are made to get the active call which the application is currently dealing with.  The other party could end the call at any time and the system is completely asynchronous and multi-threaded and it is highly likely that no call could exist the next time you check for it.  The exception being thrown was part of the null-checking strategy which has proved highly effective in reducing NPEs.  Instead of a null being returned from a method, a checked exception is returned: CallDoesNotExistException.  So this exception could happen in normal application flow and must be handled by application logic.

As it turned out the fix was remarkably elegant once the functionality as a whole was understood (read remembered).  A catch for CallDoesNotExistException was added to the catch-all handler which would navigate the user out of the process they were in to one of the two possible application states fixing similar issues in the entire application.  This change was helped by the fact that CallDoesNotExistException is task specific and other parts of the application could easily identify the issue in the code, as opposed to a generic exception which would be almost impossible to identify whether it was checked or not.