Programming Tutorials Browser Tutorials Articles Struts Tutorials Hibernate Tutorials

Search: 

  Tutorial: Use JNDI to share objects between different virtual machines - JavaWorld July 1999

Use JNDI to share objects between different virtual machines - JavaWorld July 1999

Tutorial Details:

Use JNDI to share objects between different virtual machines
Use JNDI to share objects between different virtual machines
By: By Thomas E. Davis
Share remote objects between different virtual machines without the need for an object request broker
efore I turn to this month's tool, I would like to address feedback from my previous article . I'll respond to reader comments on better design, performance problems, and bugs.
Better design
One reader commented that the Cachetable I presented in last month's column violates the Liskov Substitution Principle (see Resources ). This principle basically states that if B is a subclass of A, and C is a subclass of A, then B should be able to subclass C without any problems, and vice versa. In other words, any class that currently extends Hashtable should be able to also extend Cachetable without any side-effects. It wasn't my original intention to support this notion, but the reader is correct in asserting that it is good object-oriented design.
Performance problems
A few programming veterans immediately noticed that the ping() method has a glaring flaw: it's synchronized ! This means that the cache is locked during house cleaning, which leads to performance issues if you have a rather large collection. This issue can be resolved by incorporating reader/writer locks, but that topic is out of the scope of this series. If you're interested, you can read more about reader/writer locks in Part 7 of Java Toolbox columnist Allen Holub's series on thread issues.
Bugs
One reader pointed out that the get() method has a potential for NullPointerException s. The return value from super.get() isn't checked, and could therefore be null if a bad key is passed in. We can avoid this with a simple change:
public synchronized Object get( Object key ) {
Object o = super.get( key );
if( o != null )
{
return( ( (TimeWrapper) o ).getObject() );
}
else
{
return null;
}
}
Introduction to this month's 'cool tool'
This month's tool allows you to share objects between different virtual machines. It also allows you to store an object, have a process die, and then be able to retrieve that object once the process restarts. All of this is achievable without the complexity of database mapping or remote object architectures (like CORBA and EJB). The key concepts for this tool are serialization, persistence, and JNDI. Serialization allows you to "package" an object instance for storage and transfer. Persistence is the storage part that requires the serialization. And JNDI is Sun's standard API for interfacing with directory and naming servers. I will discuss each concept briefly, then dive into the tool itself.
Serialization and persistence
Serialization is the technique by which an object can store and restore its state, usually to and from a stream of bytes. When you serialize an object, you're basically breaking it down into its most primitive values (integers, booleans, and strings). These primitive values must be managed in a predetermined format and order so that you can deserialize the object, thus restoring the object to its original state.
Support for serialization allows an object to be persistent. In the simplest terms, this means that an object can survive from one program instance to another. For example, let's say you start up a Java program with some sort of widget. You modify the widget in some manner -- changing its color, for example. You stop the application. Then, the next time you run the application, the widget is magically the same color as when you last stopped the application. This is accomplished by simply serializing the widget to a file when the application stops, and deserializing the widget from the same file when the application starts. The file will be very small, because it only contains the integer value representing the color of the widget.
Being the wonderful language that it is, Java handles serialization for you (in JDK 1.1 and later versions). All you have to do is make your object implement the java.io.Serializable interface, and it's automatically serializable; there are no methods to be implemented. Actually, serialization isn't quite that simple. There are a few other little details that you should be aware of, such as dealing with nested containers and transient data (information that isn't vital to the object's state, and can be discarded). But these topics are outside of the scope of this article.
( Note: If you happen to be unlucky enough to still be working with the 1.02 version of the JDK, head over to ACME Laboratories for a great set of serialization utilities (see Resources for a link to this site). Not only do they work with the old JDK 1.02, but they're free!)
Now that you understand the basics of packing up and storing an object, we can talk about transferring that object to a remote server and then finding it again when needed. This is where JNDI comes in.
JNDI and directory services
The Java Naming and Directory Interface (JNDI) is a high-level API that allows you, the programmer, to work with many different naming and directory services through a single consistent interface. A naming or directory service, as its name implies, is a service that allows you to store and query names-relative information. This data can be the names of computers (as in the DNS), the login information of users (as in the NIS), or the names and addresses of people (which can be stored in X.500 or LDAP).
Not only does JNDI abstract the interfaces to the diverse naming systems, but it goes one step further and allows you to store and retrieve actual objects. The only catch is that the objects must be serializable. When an object is placed into or retrieved from a naming service, it is serialized into a stream of bytes for transport over the network and for storage.
The JNDIHashtable
This month's tool, the JNDIHashtable , uses the power of serialization, persistence, and JNDI to store objects on a remote server, rather than in local memory. The tool extends a standard Hashtable and should be used like one (though, as the reader feedback above points out, it doesn't conform to the Liskov Substitution Principle). When you put an object into the JNDIHashtable , it is actually serialized and transported to the naming server. When you ge an object out, the tool looks for the object on the remote server, retrieves it, and returns it to the process. I originally wrote this tool to help overcome a problem with stateful-session Enterprise JavaBeans.
Session beans are supposed to be short-lived single-client objects. The client connects to the bean (remote object), calls a couple methods, then disconnects and everything is done. Stateful-session beans are a hybrid type; they allow the client to disconnect from the object before finishing all of its work, and then reconnect at a later time.
The problem with session beans is that you need to keep track of a handle in order to reconnect to them. A handle is like a reference to an object in local memory, and in fact that's what it is, except that the object in local memory knows how to find and connect to a remote object.In my case, I was accessing the beans from multiple Web servers. Each time a Web page was accessed, a server-side script would run. The script needed to use a particular bean each time it ran. Due to a load-balancing mechanism on the front end of the Web servers, there was no guarantee that a user's browser would connect to the same Web server for subsequent requests. This meant that I couldn't store any state information, like the bean's handle, in the Web server's process space. By using the JNDIHashtable , I could store the bean's handle (and any other data) in the naming server (remotely) and access it from whichever Web server executed the next script.
However, in order to do this cleanly, we must add a couple restrictions to the way objects are put into the tool:
The key must be a String
the value object must be serializable
Why does JNDIHashtable have these restrictions? Because the object that you put into the JNDIHashtable isn't stored in the local memory of the running virtual machine; it is serialized and stored in a naming service. The naming service must be accessible via JNDI. This is how other applications running in separate virtual machines can access the same objects. All of the applications that are using the JNDIHashtable can share objects with each other.
The code
Coding the JNDIHashtable is simply a matter of extending Hashtable and overriding all of the necessary methods to ensure that objects are stored on the remote server rather than in local memory. In this article, I'm only going to cover the basics: the put() , get() , and remove() methods, and keys (get a list of all object mappings). The complete code can be found here:
JNDIHashtable.java .
We start out with the constructors. These are simply a redeclaration of the standard Hashtable constructors, except for one minor difference: the connection to the remote server. You'll see that the first constructor calls the second, and the second calls the third. The third constructor performs the connection by calling the connect() method. The connect() method connects to the naming service via JNDI. The Context object is the handle to the naming service; more on that in a moment.
import java.util.*;
import javax.naming.*;
public class JNDIHashtable extends Hashtable
{
private Context context;
public JNDIHashtable() {
this( 101 );
}
public JNDIHashtable( int initialCapacity ) {
this( initialCapacity, (float) 0.75 );
}
public JNDIHashtable( int initialCapacity, float loadFactor ) {
super( initialCapacity, loadFactor );
connect();
}
In order to connect to a naming service through JNDI, you have to create and use a Context object. The Context object takes a Hashtable for its constructor. You must populate the Hashtable with the necessary configuration data. This will differ from one service to th


 

Read Tutorial at: Click here to view the tutorial

Rate Tutorial:
Use JNDI to share objects between different virtual machines - JavaWorld July 1999

View Tutorial:
Use JNDI to share objects between different virtual machines - JavaWorld July 1999

Related Tutorials:

Displaying 1 - 50 of about 3115 Related Tutorials.

Java Virtual Machine
different machines. The key to Java's portability and security is the Java Virtual... code program on different kinds of machines. Most compilers produce code... on different machines. Two step compilation allows Java applets to run on many
 
Why Virtual Dedicated Hosting?
! Virtual dedicated hosting occupies the space between the relatively... Virtual Dedicated Hosting,Virtual Dedicated Server,Virtual Dedicated,Servers,Host Why Virtual Dedicated Hosting
 
Virtual Private Servers
or dedicated mail server. You can use Virtual Private Servers in the following cases... for the less powerful dedicated server, then you can use Virtual Private Server... that is simple to use while eliminating the disadvantages of the Shared approach. Virtual
 
Sharing a Table Model between JTable Components
; In this section, you will learn how to share a table model between JTable components..., a table model will essential. To share the table model between two table components... Sharing a Table Model between JTable Components
 
Classes and Objects
Classes and Objects Classes and Objects...; Objects and classes are the fundamental parts of object-orientated programming... (objects), let us consider a class employee having the employee details
 
What is the use of java?
Operating System. There are some virtual machines, such as the Java Hotspots... What is the use of java? What is the use... it is easier to use than C++ and works on the concept of object-oriented programming
 
JDO - Java Data Objects Tutorials
transferring data between in-memory Java objects and your database... JDO - Java Data Objects Tutorials, JDO Java Data Object, JDO Tutorial JDO - Java Data Objects Tutorials
 
Thread Questions
of memory do separate threads share? Circle all that are correct. Call stack Heap Static memory They don't share any memory... causes a thread to give up use of the CPU? Circle all
 
EL Implicit Objects
EL Implicit Objects EL Implicit Objects...).  Before JSP 2.0, we could  use only  a scriptlet, JSP... written between the delimiters ${ and }. In the JSP page response, the result
 
Difference between JDBC 3.0 & JDBC 4.0
Difference between JDBC 3.0 & JDBC 4.0 Difference between JDBC 3.0 & JDBC 4.0       .... These properties can be used to describe how the PooledConnection objects created
 
different borders
different borders     ... then we create different borders and we also sets the different colors. . Code...): This method is used to set the type of border to use for the left border
 
History of Java
in the early 1990s to solve the problem of connecting many household machines together. This project failed because no one wanted to use... at the end of 1998 with important additions to many different parts of Java
 
Hibernate Training
persistence engine. How to persist different types of objects using the Hibernate. How to use HQL (Hibernate Query Language) for querying objects stored in Hibernate. How to integrate Hibernate 
 
Java Data Objects
, and file systems.Java Data Objects (JDO) Why use JDO? JDO has revolutionized... JDO,What is JDO JDO - Java Data Objects..., features and benefits of JDO specification. The Java Data Objects or JDO for short
 
Draw different curves with QuadCurve2D
Draw different curves with QuadCurve2D Draw different curves with QuadCurve2D     ... how to draw different curves with the class QuadCurve2D. The QuadCurve2D class
 
Working with sessions
how to track the session between different JSP pages. In any web application user... and objects throughout the application. JSP provide an implicit object "session", which can be use to save the data specific the particular to the user
 
Class, Object and Methods
are all the body are different - different objects of the human being class... the different functions from the different classes through the several objects created... the objects are categorized in a special group. That group is termed as a class. All
 
Hibernate's Built-in criterion: Between (using with Date)
Hibernate Between Date,Criteria Query,Criteria Queries,Criteria Query... Built-in criterion: Between (using with Date)   ..., you will learn to use "between" i.e.one of the built-in hibernate
 
Application of LBS in Different Fields
with different rate plans. So rates can vary between personal and work zone according... Application of LBS in Different Fields Application of LBS in Different Fields       
 
How GPS is Different from ADF & VOR in Air Navigation
How GPS is Different from ADF & VOR in Air Navigation How GPS is Different from ADF & VOR in Air Navigation... and Magnetic Heading (MH). Pilots use these bearings and draw a line on the map
 
Show different types of Cursor
Show different types of Cursor Show different types of Cursor        ... which the dialog will use to filter the files. To make the dialog visible
 
Horizontal Rule in HTML
between any two objects in HTML.To apply horizontal rule, the <hr> tag is used... document. The use of HTML Horizontal Rule provides the user to read the document...;p>Horizontal Rule between two lines:</p> This is the first line.<hr
 
Relation between GIS and LBS
Relation between GIS and LBS Relation between GIS.... The information and communication technology is a combination of different.... However, LBS offers a two-way communication system between user and service
 
JAVA JAZZ UP - Free online Java magazine
Around the Globe   Sun released Java SE 6 Update 2 on 16 July 2007...) earlier. Before the release of the atches it was not safe to use the Java Runtime... how to use, but also equally important when to use patterns.   
 
Open Source JVM
Open Source JVM,free java virtual machine,free jvm,jvm free Open Source JVM Java Virtual Machine or JVM for short is a software execution engine to run the java programs. Java Virtual Machine is also known
 
Facelet param Tag
;  This tag is used to pass objects as variables between.... You can use this tag where a define tag is used within composition or decorate tag. We can also use this tag within include tag.  In this example, we have
 
Write a program to list all even numbers between two numbers
a program to list all even numbers between two numbers  ... for listing out all the even numbers between two numbers. For this first create a class named AllEvenNum under the java.io package. Now use the try/catch
 
Different types of event in Java AWT
Different types of event in Java AWT.... The generated event is passed to every EventListener objects that receives.... The generated event is passed to every objects that is registered to receive such type
 
Using Super class Variables With Sub-classed Objects
Using Super class Variables With Sub-classed Objects Using Super class Variables With Sub-classed Objects  ...;head> <title>To Use Superclass Variables With Subclassed Objects<
 
Open Source XML Editor
on any Java 2 virtual machine (JDK1.2.2 or higher). The application... to display elements, or use Jaxe within other applications. Jaxe... Paper is to provide an introduction to different features XML editors can have
 
different Font
different Font different Font                           
 
Comparing two Dates in Java with the use of after method
objects we can use after() method of the java.util.Date class. The after... Comparing two Dates in Java with the use of after method, after method... with the use of after method       
 
Factory Pattern
is to delegate responsibility among different objects. This kind of partitioning is good... it's subclasses to specify the objects to be created or delegate responsibility to one... the different task and is optimized for different kind of data.  A factory
 
Methods - Declaring
: Everything between square brackets, "[" and "]", is optional. [access... the method returns. Use void if the method doesn't return a value... definition. These are the names that you use in your method. Formal
 
Use of Text Field
Use of Text Field, Text box, Text Area, Checkbox,Dropdownlist and Radio...} --> Use of Text Field, Text box, Text Area, Checkbox,Dropdownlist... are allowed to enter or select different types of information. A form contains form
 
Open Source Games
are fundamentally different to most types of software. I will suggest a few reasons why... You can use open source software to make yourself more productive, but the open... that game developers or hobbyists could use to create real-time strategy (RTS) games
 
How to use this keyword in java
and local variables same. Now to avoid the confliction between them we use... in Java How to use "this" keyword in java... of the program for the illustration of how to what is this keyword and how to use
 
change one type of color in between more colors
How to change one type of color in between more colors. How to change one type of color in between more colors.... Color Balance: Now change the color so we have to use "Color Balance"
 
Simple Date example
example that shows how you can use different constructors of Date. We can construct... with the year value 1999, month value 8 and day value 7. Here is the example... Parameterized constructor ==>Tue Sep 07 00:00:00 GMT+05:30 1999
 
How to use List in velocity
How to use List in velocity How to use List...;   This Example shows you how to use List in velocity... but it has some different and enhanced functionality.   
 
Difference between JSP 2.0 & JSP 2.1
Difference between JSP 2.0 & JSP 2.1 Difference between JSP 2.0 & JSP 2.1     ... expressions in JSP. EL provides the ability to use run-time expressions
 
Difference between Servlet 2.5 and Servlet 2.4
Difference between Servlet 2.5 and Servlet 2.4 Difference between Servlet 2.5 and Servlet 2.4    ... changes to the web.xml file to make it more convenient to use
 
Java Interview Questions - Page 12
. Deserialization is the process of restoring these objects. Question... different. Some syntax may be similar. Question: What is a Container... (including other containers) through the use of layout managers, which use
 
MockCentral
different cases when many mock objects were in play involved lots of duplication...; MockCentral is an easy-to-use, fully-featured set of tools that provides a new approach to java software testing using mock objects. It enables the developer
 
JavaScript array of objects
JavaScript array of objects JavaScript array of objects          ... that help you in understanding JavaScript array of objects. For this we are using
 
Use of "descendant" in XPath expression
Use of "descendant" in XPath expression Use... in Java tutorial you will learn use of descendant in XPath expression. "...; contains information related to name, age, gender of different persons. Here
 
Use of "parent" in XPath expression
Use of "parent" in XPath expression Use of "parent... you have studied how to use child axis in XPath expression . Now this section will describe the use of "parent" axis. "parent" axis
 
Open Source Connection pools written in Java

 
Use of "ancestor" in XPath expression
Use of "ancestor" in XPath expression Use... the use of ancestor in XPath expression. "ancestor" selects parent..." contains information related to name, age, gender of different persons
 
Java & JEE books Page4
loading, and more. Early Java virtual machines were simple bytecode interpreters... create some nice scripts that will use time delays to make things happen. Let's... is going to be the function you want to use. This function was named "myfunction
 
Site navigation
 

 

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2006. All rights reserved.