Archive for the ‘ Java Programming Language ’ Category

Java 6.0 APIs

Java 6.0 introduces many Application Programming Interfaces and there are many enhancements in existing classes especially in collection APIs. The summary of changes in collection framework is listed below…

New Interfaces

  • Deque
  • BlockingDeque
  • NavigableSet
  • NavigableMap

New Classes

  • ArrayDeque
  • LinkedBlockingDeque
  • ConcurrentSkipListSet
  • ConcurrentSkipListMap
  • AbstractMap.SimpleEntry
  • AbstractMap.SimpleImmutableEntry

Updated Classes

  • LinkedList
  • TreeSet
  • TreeMap
  • Collections

Deque and ArrayDeque

Deque is the abbreviation for Double Ended Queue. It is a collection that allows to add and remove elements from both the ends. The implementations of Deque can be used as Stack or Queue. The Deque implementations use the insertion and remove method in two types,one used to throw exception to indicate failed operation while another one returns a special value as an indicator, in this case we often use null to indicate that collection is empty. So need to block the insertion of null values

ArrayDeque

ArrayDeque is one of the implements Deque. It has the following properties

  • No capacity restrictions.
  • Faster than stack and linked list when used as stack and queue.
  • ArrayDeque is considered to be not thread Safe.

BlockingDeque and LinkedBlockingDeque

BlockingDeque has similar properties of Deque with some additional functionalities. If we are trying to insert an element in to a BlockingDeque, that is already full, it will wait till the space becomes available to insert given element. The time limit to wait can be customized by the developer. BlockingDeque insertion and removal methods come in four types

  • Methods that throws exception
  • Methods that returns special values
  • Methods that waits indefinitely till space to available for insertion
  • Methods that waits for a specified time for space to be available for insertion

NavigableSet and ConcurrentSkipListSet

NavigableSet methods returns the closest matches of a given element for elements in the collection. NavigableSet methods lower, floor, ceiling, and higher return elements less than, less than or equal, greater than or equal, and greater than of a given element respectively. It returns null if there is no such element. NavigableSet can be accessed and traversed in either direction. ConcurrentSkipListSet is one of the implementations of NavigableSet.

NavigableMap and ConcurrentSkipListMap

It is similar to NavigableSet used to store key,values pairs. ConcurrentSkipListMap is one of the implementations of NavigableMap.

AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry

These are the static classes inside abstractMap class used to hold key, value pairs. The difference between these two classes is that AbstractMap.SimpleEntry allow programmers to set the value using setValue method while the AbstractMap.SimpleImmutableEntry throws UnsupportedOperationException if we try to set the value.

Modified classes

There are few changes introduced in the java 6 collections like LinkedList modified to implement Deque, TreeSet is modified so that it can implement NavigableSet and TreeMap modified to implement NavigableMap.

Java6.0 new features allows the programmer to develop easier retrieval of elements in desired way.

Julian is a professional content writer on Java Development at Telious Technologies.

Article Source: http://EzineArticles.com/?expert=Julian_Jaic

  • Digg
  • Mixx
  • Faves
  • Propeller
  • StumbleUpon
  • Tumblr
  • Yahoo! Buzz
  • del.icio.us
  • Facebook
  • Reddit
  • RSS
  • Technorati

Memory Leaks in Java

One of the beauties of using Java programming language is that the programmers need not worry about the memory allocation and freeing of objects. We simply declare and initialize objects and JVM (Java Virtual Machine) will take care of freeing them when they are no longer in use by any application through a mechanism called ‘garbage collection’. Before we start our topic, let us check how the memory is allocated for the objects.

Generally, the objects which are created using the ‘new’ keyword are allocated in ‘memory heap’ and the objects that are used for the method arguments and method variables are created into a ’stack’. When these objects are no more referred or when they are out of scope, they are eligible for garbage collection. The statement System.gc(); only suggest the JVM to perform a garbage collection and we can’t force the JVM to do it, but the JVM may do it when the system is running short of memory.

Though JVM manages the memory, we can’t be sure about the memory leaks. One can still have memory leak by poor programming (may be by keeping the references to null for too many objects in an application). If the Java program is written to run continuously in a server,even small memory leaking is risky. And a relatively small program also can reach the memory limit by using large number of temporary objects or objects that take large amount of memory. In such cases, Java holds memory for the unused objects and the application may run out of memory. JVM memory leaking is not dangerous as much as C++ memory leaking where the memory does not return to the operating system after the crash of the application. But in java programs, objects are created in the memory given to the JVM by the operating system. So when the JVM is closed, memory will return back to the OS.

If, there comes java.lang.OutOfMemoryError exception while executing a java application, your program may have memory leak. Finding the reason for memory leak can be difficult. By watching some of the common problems we can control the memory leaks. Some of the collection classes which is declared as static or which lives for the lifetime of an application such as hashmaps and vectors are common places where we can find memory leaks. Another common place is when we register an event listener toa class and forget to unregister it when it is not needed. We can use debugging tools like JProbe Suite, Optimizeit Enterprise Suite, Win32 Java Heap Inspector etc for fixing the memory leaks in java programming.

Julian is a professional content writer on java development and now working at Telious Technologies.

Article Source: http://EzineArticles.com/?expert=Julian_Jaic

  • Digg
  • Mixx
  • Faves
  • Propeller
  • StumbleUpon
  • Tumblr
  • Yahoo! Buzz
  • del.icio.us
  • Facebook
  • Reddit
  • RSS
  • Technorati

Java Garbage Collection

What is garbage collection?

It deals with identifying and freeing the memory of java application that are not used for a long time. There are two type garbage collection techniques, namely explicit and implicit methods.

Implicit Garbage collection and Explicit Garbage collection

Java run time system can invoke the garbage collector automatically so that the user never need to bother about the memory space when creating an object. This is implicit Garbage Collection.

Explicit Garbage Collection means the user is doing the collection intentionally. This is achieved by using System. gc();

Steps in a garbage collection

1. garbage collector searches for objects that are referenced in code.

2. garbage collector finds the unreferenced code.

3. garbage collector frees unreferenced objects and add their memory space to heap.

Methods in System

1) collect()

Request to the garbage collector to reclaim the memory to heap. By using this method it not sure that any inaccessible memory is reclaimed

public static void Collect()

2)keepAlive()

This method is used to ensure the existence of an object. Using this method we can add a value reference counter so it is not reclaimed by the garbage collector, we have to pass the object name as the parameter

public static void KeepAlive(Object obj);

Different Garbage Collector

Reference counting

One of the simple methods is reference counting. This type of garbage collection is very slow. In this type of GC each object will have a reference counter that will hold the value of how many times it has been referred. When a reference to an object is made by attaching a handle to it then the counter value will be incremented by one every time the handle goes out from the object or set to null, that means the reference is no longer exists the counter value will decremented. Thus reference count is small but constant work happens during the entire life time of your program. The garbage collector move through the entire list of the object. When GC find an object with reference count zero or null, it releases the storage. The main problem with the Reference count is when the object has circular reference then the GC cant find an object with zero value. Finding the self reference object need an extra effort. This is why reference GC is not being used in JVM(Java Virtual Machine)

Copy garbage collector

>If you need faster GC it is not possible with the reference counting. The other GC is based on the idea that any non-dead object can access easily whether they are in stack or static storage. This chain must go through several object. Thus you can find all the live object. For each handle you find, you must trace in to the object that the handle points and then trace all the handles of that object they points. This will continue after moving through the entire web. Each object that you passes through must be alive. The problem with self referential groups can be avoided by this. In this collector type JVM use adaptive garbage collection method. What it does is locating the object according to the variant currently being used. Each live object that found is copied from the one heap to another discarding all the garbage. In new heap objects are packed end to end.

Problem with this technique is you need to keep twice the memory that you actually need. The second issue is in stable program, where the garbage will be very small. But still the copy collector copy all the memory from one to another.

Mark and Sweep

Mark and Sweep uses same technology as the Copy garbage collector but the main difference is that it will not move the live object. In this kind of GC when it finds a live object the object is marked by setting the flag. Only after the marking process is finished the sweep occurs. In sweep all dead objects(unmarked) are released and no copying happens.

Through Garbage collection techniques the memory can be effectively managed in a java application.

Julian is a professional content writer on Java Development and now working at Telious Technologies.

Article Source: http://EzineArticles.com/?expert=Julian_Jaic

  • Digg
  • Mixx
  • Faves
  • Propeller
  • StumbleUpon
  • Tumblr
  • Yahoo! Buzz
  • del.icio.us
  • Facebook
  • Reddit
  • RSS
  • Technorati

Software Development | Java RMI

Basic Model of a JAVA RMI: Execution of distributed objects in Java is possible with the help of Java RMI. A client can access a Java Object Host which is on a remote virtual machine from any JVM. It is a two step procedure. The first step is about execution of the clients and servers in Java. This will allow them to have an inherent object-oriented appearance and objects will interact with all the characteristics of Java. So it means that we can access/run a server object from any java virtual machine (JVM) therefore, we can achieve the platform independence.

Second is that the Java RMI’s fundamental model always has a client program, and this client program is used to approach the remote objects from any Java virtual machine. The connection between a client and remote objects need to reference an object, which is hosted by a server program. Remote server objects can be located by a server in two different ways. These two procedures have their own methods to give remote reference to the client. These procedures are,

• Explicitly.

• Implicitly.

Both are used for “obtaining a remote reference”.

Java RMI Architecture:

To create a Math service using Java RMI I have followed these steps.

1. Define a remote interface

2. Implementation of the server

3. Implementation of the client

4. Compile the source code

5. Start Java RMI registry, server and then client.

Create the Remote Interface:

In Java RMI an interface is used to extend the “java.rmi.Remote” interface. Remote interface doesn’t have any method of its own, and it is used for tagging the remote objects, which makes possible to identify as it is. (Harold E. R., 2000). Set of remote methods also declared in the interface. Every single remote method must declare “java.rmi.RemoteException” or a superclass of the “RemoteException” in its throws section, in addition to any application’s specific exception.

Example which I have used in this paragraph for remote interface, “bite.example.SampleServer”. It declares the four methods, “Addition”, “Subtraction”, “Multiplication” and “Square”.

Following is the source code for “SampleServer.java”.

Sample Server

package bite.example;

import java.rmi.Remote;

import java.rmi.RemoteException;

public interface SampleServer extends Remote

{

public int addition(int x, int y) throws RemoteException;

public int subtract(int x, int y)throws RemoteException;

public int multiply(int x, int y)throws RemoteException;

public int square(int x)throws RemoteException;

public int getValue()throws RemoteException;

public String getLastOp()throws RemoteException;

}

Implementation of Sever:

In this context our “server” class exports the remote object and this server class holds a “main” method, this produce an instance of the remote object implementation. Then it combines that instance to a name in a Java RMI registry. The class which holds this “main” method possibly the implementation class by itself or another class completely.

In the class “Server” we declare the “main” method for server, and it also perform the remote interface SampleServer. Our server’s “main” method follows these two steps. A new remote object is produced and export in first step, second step is about the registration of an object with a Java RMI registry.

Source code for class “SampleServerImpl.java” is as following.

Sample Server Impl.

package bite.example;

import java.rmi.registry.Registry;

import java.rmi.registry.LocateRegistry;

import java.rmi.RemoteException;

import java.rmi.server.UnicastRemoteObject;

public class SampleServerImpl implements SampleServer {

private int value =0;

private String lastOp;

SampleServerImpl(){

}

public int addition(int x, int y) throws RemoteException {

value = x + y;

lastOp = “ADDITION”;

return value;

}

public int subtract(int x, int y)throws RemoteException{

value = x – y;

lastOp = “SUBTRACTION”;

return value;

}

public int multiply(int x, int y)throws RemoteException{

value = x*y;

lastOp = “MULTIPLY”;

return value;

}

public int square(int x)throws RemoteException{

value = x*x;

lastOp = “SQUARE”;

return value;

}

/* Resource properties */

public int getValue() throws RemoteException {

return value;

}

public void setValue(int value) {

this.value = value;

}

public String getLastOp()throws RemoteException {

return lastOp;

}

public void setLastOp(String lastOp) {

this.lastOp = lastOp;

}

public static void main(String args[]) {

try {

//Create and export a remote object

SampleServerImpl obj = new SampleServerImpl();

SampleServer stub = (SampleServer)UnicastRemoteObject.exportObject(obj, 0);

//Register the remote object with a Java RMI registry

//and bind the remote object’s stub in the registry

Registry registry = LocateRegistry.getRegistry();

registry.bind(“SampleServer”, stub);

System.err.println(“Server ready”);

} catch (Exception e) {

System.err.println(“Server exception: ” + e.toString());

e.printStackTrace();

}

}

}

Implementation of Client:

Client class acquires a “stub” for the registry on the server’s host, and it is searches remote object’s stub in the registry by their names, and then it invokes the “Addition”, “Subtraction”, “Multiply” and “Square” methods on the remote object using stub.

Source code for the Client is following.

Sample Client

package bite.example;

import java.io.*;

import java.rmi.registry.LocateRegistry;

import java.rmi.registry.Registry;

import java.util.Scanner;

public class SampleClient {

public static void main(String[] args) {

String host = (args.length start java -Djava.rmi.server.codebase=file:C:/rmi/ -Djava.rmi.server.name=192.168.0.03 bite.example.SampleServerImpl”

And then I have got the output “Server ready”

Start the Client: Final step is to start the client. When server was ready I open another window of command prompt line and then run the client as follow “C:\rmi>java bite.example.SampleClient”

http://EzineArticles.com/?Java-RMI&id=4674799

  • Digg
  • Mixx
  • Faves
  • Propeller
  • StumbleUpon
  • Tumblr
  • Yahoo! Buzz
  • del.icio.us
  • Facebook
  • Reddit
  • RSS
  • Technorati

What is Java Object Initialization?

The concept of objects in a broad sense can be described as a collection of data along with the methods to manipulate the corresponding data. The Objects are be loaded into the memory before processing. In main memory the object has a state determined by its instance variables and their values, which can be processed and evolved throughout its lifetime. The newly-created object should have a newly-allocated memory (heap) to accommodate the object’s instance variables, this is done by Java virtual machine (JVM).

Object initialization is very important in programming, as it is a common source of bugs. The Java Programming language provides different built-in mechanisms to ensure proper initialization of the memory occupied by a newly-created object, there by helping the objects to get a valid initial state.

The Java Programming language offers three mechanisms to ensure proper initialization of newly created objects.

  • Constructors.
  • Instance variable initialization.
  • Instance initialization.

When we are creating an object using new operator or the new Instance() method of class, JVM allocates memory for it, then Java virtual machine will run the initialization code before we use the newly-allocated memory.

Constructors

Constructors are methods, with a set of parameters and a body of code and has the same name as the class but has no return type. The constructors can be overloaded by varying the number, types, and order of parameters. When we are creating new instance using new keyword we often provide a constructor that initialize the Object. If we are using class that has no constructor defined, the compiler will automatically generate a default constructor for the class. This constructor has no parameter and has empty body, this ensures that each class has at least one constructor.

class Demo

{

int a;

public Demo()

{

// the initialization code for instance variables

a=0;

}

}

Instance variable initialization

In an instance variable initialization method java uses an equals sign and expression technique to initialize the instance variable.

class Demo

{

private int a = 1; //this evaluate a with a value of 1

}

Instance initialization

Instance initialization is also known as instance initialization block, which is one of the alternatives to Instance variable initialization. It is very useful in following situations

  • Initializer code need to catch exceptions.
  • Initializer code need to do calculations that can’t be expressed with an instance variable initializer.
  • If class has multiple constructors – no need to repeat the same initializing code in all constructors.
  • When we use anonymous inner classes, which normally do not have constructors.

class Demo

{

private int a;

//intializer

{

a=2;

}

}

One of the main properties of initializers is they cant make forward reference, as the initializers are executed in textual order.You have to make sure that the referring of instance variable should be only after it is initialized.

Default initial values

If we are not providing any explicit initialization method to variables including instance and class variables, they will be initialized according to their type. Each data type has its own default initial values. The local variable must be initialized explicitly before use.

e.g boolean-false

int – 0

Java’s initialization mechanisms help the programmer to ensure that objects we design have a valid and predictable state.

Julian is a professional content writer on Java Development and now working at Telious Technologies.

  • Digg
  • Mixx
  • Faves
  • Propeller
  • StumbleUpon
  • Tumblr
  • Yahoo! Buzz
  • del.icio.us
  • Facebook
  • Reddit
  • RSS
  • Technorati

Ruby on Rails vs Java – RailsEnvy.com Commerical

Gregg Pollack and Jason Seifer from RailsEnvy.com do some Ruby on Rails commercials in the same style of the Mac vs PC ads.

  • Digg
  • Mixx
  • Faves
  • Propeller
  • StumbleUpon
  • Tumblr
  • Yahoo! Buzz
  • del.icio.us
  • Facebook
  • Reddit
  • RSS
  • Technorati

Java Lesson – Coding a Form

JavaServer Pages and Java Servlets are programs executed by a Web server to produce Web pages which are sent to a client Web browser in response to a request from the browser. This course by Arthur Griffith not only demonstrates how to write them, it also shows how to deploy them to a server and make them run in response to a request. Both Servlets and JavaServer pages can read from files, including the use of SQL to read from a relational database, and use the information to construct a Web page. To begin learning today, simply click on one of the Java 2: JSP and Servlets lessons.

  • Digg
  • Mixx
  • Faves
  • Propeller
  • StumbleUpon
  • Tumblr
  • Yahoo! Buzz
  • del.icio.us
  • Facebook
  • Reddit
  • RSS
  • Technorati

The Basics Of Java Programming

Just a tutorial to cover the very basics of Java, also the first time I’ve used Windows Movie Editor to make.

  • Digg
  • Mixx
  • Faves
  • Propeller
  • StumbleUpon
  • Tumblr
  • Yahoo! Buzz
  • del.icio.us
  • Facebook
  • Reddit
  • RSS
  • Technorati