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

August 12, 2011

Tomcat 7.0 (No JDK required)

Today when i was installing tomcat 6 on my local system i noticed that it didn't asked me to install JDK first like it is use to ask in versions previous than 5.5.Most of us who install Tomcat on our development machines wouldn’t have noticed that Tomcat versions before 5.5 required the full blown Java Development Kit (JDK) to be installed on the machine. Just installing the Java Runtime Environment (JRE) wasn’t enough. The JDK is meant for developers to be able to compile Java programs, and has the development tools such as the compiler, debugger and other development libraries. Tomcat versions prior to 5.5 used the Java compiler that comes with the JDK to compile JSP pages at runtime and consequently required a full blown JDK.

Tomcat versions 5.5 and above have a Java compiler (the Eclipse JDT Java compiler) packaged along with it. Now, this is used to compile the JSP pages dynamically instead of the JDK compiler. Hence, it is enough if we just install JRE starting from Tomcat version 5.5 and above.

July 28, 2011

Java 1.7

I have been reading quite a lot about Java 1.7. There are articles about what's new, some code examples, some benchmark to compare performance with previous version of Java and discussion on when it will be released. I have decided to regroup all I have discovered in this article so that I and maybe you, won't have to spend hours surfing the web to find all this information. Don't hesitate to leave a comment if I missed something.
What's new in Java 1.7?

So what made it through is the following:
§ Strings in switch
§ Automatic Resource Management
§ Improved Type Inference for Generic Instance Creation (diamond)
§ Simplified Varargs Method Invocation
§ An omnibus proposal for better integral literals
§ Language support for Collections
§ Language support for JSR 292

These features are divided in different categories:

VM
§ Compressed 64-bit object pointers
§ Garbage-First GC (G1)
§ JSR 292: VM support for non-Java languages (InvokeDynamic)

lang
§ SR 294: Language and VM support for modular programming
§ JSR 308: Annotations on Java types
§ JSR TBD: Small language enhancements (the Project Coin I was talking about)
§ JSR TBD: Project Lambda

core
§ Modularization (Project Jigsaw)
§ Upgrade class-loader architecture
§ Method to close a URLClassLoader
§ Unicode 5.1
§ Concurrency and collections updates (jsr166y)
§ JSR 203: More new I/O APIs for the Java platform (NIO.2)
§ SCTP (Stream Control Transmission Protocol)
§ SDP (Sockets Direct Protocol)
§ Elliptic-curve cryptography (ECC)

client
§ XRender pipeline for Java 2D
§ Forward-port 6u10 deployment features
§ Create new platform APIs for 6u10 graphics features
§ Nimbus look-and-feel for Swing
§ Swing JLayer component

web
§ Update the XML stack
As you can see there is a lot of stuff. I personally tried the new Garbage Collector (G1) a few months back and was really impressed by the performance. Unfortunately the JVM was crashing every few hours so it couldn't be used for production. This GC is available in Java 1.6 as well but same thing, it crashes every so often.
I think that's it for the new features. Maybe it's a good idea to see some code examples now.

July 23, 2011

Dependency Injection

Java components / classes should be as independent as possible of other Java classes. This increases the possibility to reuse these classes and to test them independently of other classes(Unit Testing). To decouple Java components from other Java components the dependency to a certain other class should get injected into them rather that the class itself creates / finds this object.

A class A has a dependency to class B if class uses class B as a variable.

If dependency injection is used then the class B is given to class A via

the constructor of the class A - this is then called construction injection

a setter - this is then called setter injection

The general concept between dependency injection is called Inversion of Control. A class should not configure itself but should be configured from outside.

A design based on independent classes / components increases the re-usability and possibility to test the software. For example if a class A expects a Dao (Data Access object) for receiving the data from a database you can easily create another test object which mocks the database connection and inject this object into A to test A without having an actual database connection.

A software design based on dependency injection is possible with standard Java.

July 13, 2011

Importing a class from default package - Impossible

Did you know that classes in the ‘default package’ (classes that don’t have a package) cannot be imported from classes that do have a package?

I did not know that.

Try it:



Now try to compile your code:
>javac Class1.java

>javac package2\Clazz2.java -cp .

package2\Clazz2.java:3: ‘.’ expected
import Class1;
^
package2\Clazz2.java:3: ‘;’ expected
import Class1;

How stupid is this?
Is this why omitting package is deprecated?

May 18, 2011

MVC1 Vs MVC2

A MVC Model 1 architecture consists of a Web browser directly accessing Web-tier JSP pages. The JSP pages access Web-tier JavaBeans that represent the application model, and the next view to display (JSP page, servlet, HTML page, and so on) is determined either by hyperlinks selected in the source document or by request parameters. A Model 1 application control is decentralized, because the current page being displayed determines the next page to display. In addition, each JSP page or servlet processes its own inputs (parameters from GET or POST). In some Model 1 architectures, choosing the next page to display occurs in scriptlet code, but this usage is considered poor form.

A MVC Model 2 architecture introduces a controller servlet between the browser and the JSP pages or servlet content being delivered. The controller centralizes the logic for dispatching requests to the next view based on the request URL, input parameters, and application state. The controller also handles view selection, which decouples JSP pages and servlets from one another. Model 2 applications are easier to maintain and extend, because views do not refer to each other directly. The Model 2 controller servlet provides a single point of control for security and logging, and often encapsulates incoming data into a form usable by the back-end MVC model. For these reasons, the Model 2 architecture is recommended for most interactive applications.

March 9, 2011

XML Parsers

Evolution of the XML Parsing/Manipulation using Java

The combination of Java and XML has been one of the most attracting things which had happened in the field of software development in the 21st century. It has been mainly for two reasons - Java, arguably the most widely used programming language and XML, almost unarguably the best mechanism of data description and transfer.

Since these two were different technologies and hence it initially required a developer to have a sound understanding of both of these before he can make the best use of the combination. Since then there have been a paradigm shift towards Java and we have seen few interesting technologies getting evolved to make this happen. Some of them are:-

SAX - Simple API for XML Parsing

It was the first to come on the scene and interestingly it was developed in the XML-Dev maling list. Evidently the people who developed this were XML gurus and it is quite visible in the usage of this API. You got to have a fair understanding of XML, but at least Java developers got something to combine the two worlds - Java and XML in a structured way. It instantly became a hit for the obvious reasons.

Being the first in the evolution ladder, it obviously had only the basic support for XML processing. It is an event-based technology, which uses callbacks to load the parts of the XML document in a sequential way. This effectively means you can't go back to some part which was read/processed previously - if you do have such a requirement then you would need to store/manage the relevant data yourself.

Since this API does require to load the entire XML doc and also because it offers only a sequential processing of the doc hence it is quite fast. Another reason of it being faster is that it does not allow modification of the underlying XML data.

Interested in going through a step-by-step implementation (with explanation of the complete source code) of a simple SAX Parser in Java using SAX2 APIs? Here is it for you - SAX Parser Implementation in Java >>

DOM - Document Object Model

The Java binding for DOM provided a tree-based representation of the XML documents - allowing random access and modification of the underlying XML data. Not very difficult to deduce that it would be slower as compared to SAX.

The event-based callback methodology was replaced by an object-oriented in-memory representation of the XML documents. Though, it differs from one implementation to another if the entire document or a part of it would be kept in the memory at a particular instant, but the Java developers are kept out of all the hassle and they get the entire tree readily available whenever they wish.

JAXP - Java API for XML Parsing

The creators and designers of Java realized that the Java developers should not be XML gurus to use the XML in Java applications. The first step towards making this possible was the evolution of JAXP, which made it easier to obtain either a DOM Document or a SAX-compliant parser via a factory class. This reduced the dependence of Java developers over the numerous vendors supplying the parsers of either type. Additionally, JAXP made sure that an interchange between the parsers required minimal code changes.


February 23, 2011

How Scrollable ResultSets Work?

JDBC result sets are created with three properties: type, concurrency and holdability.
The type can be one of
-TYPE_FORWARD_ONLY
-TYPE_SCROLL_INSENSITIVE
-TYPE_SCROLL_SENSITIVE.

The concurrency can be one of
-CONCUR_READ_ONLY
-CONCUR_UPDATABLE.

The holdability can be one of
-HOLD_CURSORS_OVER_COMMIT
-CLOSE_CURSORS_AT_COMMIT.

JDBC allows the full cross product of these. Some database like SQL 2003 prohibits the combination {TYPE_SCROLL_INSENSITIVE, CONCUR_UPDATABLE}, but this combination is supported by some vendors, notably Oracle.

The movable cursors,moving forward and backward on a resultset is one of the new features in the JDBC 2.0 API. There are also methods that let you move the cursor to a particular row and check the position of the cursor.
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);

ResultSet resultSet = stmt.executeQuery("SELECT FNAME, LNAME FROM EMPLOYEE");

while (resultSet.next()) {

. . . // iterates forward through resultSet

}

. . .

resultSet.absolute(5); // moves cursor to the fifth row

. . .

resultSet.relative(-2); // moves cursor to the third row

. . .

resultSet.relative(4); // moves cursor to the seventh row

. . .

resultSet.previous(); // moves cursor to sixth row

. . .

int rowNumber = resultSet.getRow(); // rowNumber should be 6

resultSet.moveAfterLast(); // moves cursor to position // after last row

while (previous()) {

. . . // iterates backward through resultSet

}

When a resultset type is defined then it is also significant to define whether it is readonly or updatable and type and concurrency should be in the same order as shown in the code above.If you change the order then compiler can not distinguish it.If you specify the constant TYPE_FORWARD_ONLY, it creates a nonscrollable result set, in which the cursor moves forward only. The default value of ResultSet object type is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

February 22, 2011

How JVM handles thread synchronization?

JVM associates a lock with an object or a class to achieve mutilthreading. A lock is like a token or privilege that only one thread can "possess" at any one time. When a thread wants to lock a particular object or class, it asks the JVM.JVM responds to thread with a lock maybe very soon, maybe later, or never. When the thread no longer needs the lock, it returns it to the JVM. If another thread has requested the same lock, the JVM passes the lock to that thread.If a thread has a lock,no other thread can access the locked data until the thread that owns the lock releases it.

The JVM uses locks in conjunction with monitors. A monitor is basically a guardian in that it watches over a sequence of code, making sure only one thread at a time executes the code.Each monitor is associated with an object reference. It is the responsibility of monitor to watch an arriving thread must obtain a lock on the referenced object.

When the thread leaves the block,it releases the lock on the associated object.A single thread is allowed to lock the same object multiple times.JVM maintains a count of the number of times the object has been locked. An unlocked object has a count of zero. When a thread acquires the lock for the first time, the count is incremented to one. Each time the thread acquires a lock on the same object, a count is incremented. Each time the thread releases the lock, the count is decremented. When the count reaches zero, the lock is released and made available to other threads.

In Java language terminology, the coordination of multiple threads that must access shared data is called synchronization. The language provides two built-in ways to synchronize access to data: with synchronized statements or synchronized methods.

The JVM does not use any special opcodes to invoke or return from synchronized methods. When the JVM resolves the symbolic reference to a method, it determines whether the method is synchronized. If it is, the JVM acquires a lock before invoking the method. For an instance method, the JVM acquires the lock associated with the object upon which the method is being invoked. For a class method, it acquires the lock associated with the class to which the method belongs. After a synchronized method completes, whether it completes by returning or by throwing an exception, the lock is released.

Two opcodes, monitorenter and monitorexit are used by JVM for accomplishing this task.

When monitorenter is encountered by the Java virtual machine, it acquires the lock for the object referred to by objectref on the stack. If the thread already owns the lock for that object, a count is incremented. Each time monitorexit is executed for the thread on the object, the count is decremented. When the count reaches zero, the monitor is released.

Story of a Java Program from start to end

When JVM executes a Java application, a runtime instance of JVM is born.This runtime instance invoke main() method of Java application.The main() method of an application serves as the starting point for that application's initial thread. The initial thread can in turn fire off other threads.

This thread has a program counter(PC) and Java stack.Whenever main() method is invoked, a stack frame is pushed onto the stack,this then becomes the active tack frame.The program counter in the new Java stack frame will point to the beginning of the method.

If there are more method invocations within main() method then this process of pushing new stack frame onto the stack for each method call is repeated as and when they are invoked.When a method returns, the active frame is popped from the stack and the one below becomes the active stack frame.The PC is set to the instruction after the method call and the method continues.

There is only one heap corresponding to an instance of JVM and all objects created are stored here.This heap is shared by all threads created in an application.

Inside the Java virtual machine, threads come in two flavors: daemon and non- daemon. A daemon thread is ordinarily a thread used by the virtual machine itself, such as a thread that performs garbage collection. The application, however, can mark any threads it creates as daemon threads. The initial thread of an application--the one that begins at main()--is a non- daemon thread.

A Java application continues to execute (the virtual machine instance continues to live) as long as any non-daemon threads are still running. When all non-daemon threads of a Java application terminate, the virtual machine instance will exit. If permitted by the security manager, the application can also cause its own demise by invoking the exit() method of class Runtime or System.

When main() returns,it terminates the application's only non-daemon thread, which causes the virtual machine instance to exit.

April 13, 2010

James Gosling resigns from SUN(ORACLE SUN)

James Gosling has announced via his new blog that he resigned from Oracle a week ago (April 2nd).Generally credited as the inventor of the Java programming language, Gosling created the original design for Java and implemented the first compiler and virtual machine for it. Gosling, who will be 55 this year, had been with Sun Microsystems since 1984. Oracle acquired Sun Microsystems in January this year, following five months of investigation by the European Commission's Competition Commissioner.

Prior to joining Sun Gosling wrote a version of emacs (gosmacs), and while at Carnegie Mellon University he built a multi-processor version of Unix, as well as a number of compilers and mail systems.He doesn't yet have a new job, describing himself as "blissfully unemployed" on his bio. On his blog he states "I don't know what I'm going to do next, other than take some time off before I start job hunting. "
 

Copyright 2007 All Right Reserved. shine-on design by Nurudin Jauhari. and Published on Free Templates