Process
A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space.
To facilitate communication between processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes and sockets. IPC is used not just for communication between processes on the same system, but processes on different systems.
Most implementations of the Java virtual machine run as a single process. A Java application can create additional processes using a ProcessBuilder object.
Thread
Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.
Threads exist within a process - every process has at least one. Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.
Multithreaded execution is an essential feature of the Java platform. Every application has at least one thread - or several, if you count "system" threads that do things like memory management and signal handling. But from the application programmers' point of view, you start with just one thread, called the main thread. This thread has the ability to create additional threads.
Preferred means of creating multthreaded application in J2SE5.0
Implement the Runnable interface and use build-in methods and classes to create Threads that execute the Runnables.
Runnables are executed by an object of a class that implements the Executor interface. An executor object typically creates and manages a group of threads called a thread pool.
ExecutorService's execute method creates a new Thread inside the ExecutorService to run the Runnable passed to it as an argument and transitions that Thread from the new state to the runnable state. Method execute returns immediately from each invocation - the program does not wait for each PrintTask to finish.
ExecutorService.shutdown() method will end each Thread in threadExecutor as soon as each finishes executing its Runnable.
If the program executed more than three Runnables, additional Threads would not be created, but rather an existing Thread would be reused when it completed the Runnable assigned to it.
The code in the method main executes in the main thread which is created by the JVM and executes the main method.
The code in the run method of PrintTask executes in the threads created by the ExecutorService. When method main terminates, the program itself continues running because there are still threads that are alive. The program will not terminate until its last thread completes execution.
ref
Monday, May 14, 2007
Sunday, May 13, 2007
Collections in Java
In the early days, java platform had only two basic classes:
java.util.Vector
java.util.Hashtable
Prior to java 5.0, the Collections Framework had two major drawbacks.
The collections were untyped and worked only with anonymous Objects instead of real types like Dates and Strings.This meant that you had to perform a type cast every time you took an object out of a collection. In theory, this broke Java's compile-time type safety.
The second problem was that, for practical reasons, collections could work only with objects and not with primitive types. This meant that any time you wanted to put a number or other primitive type into a collection you had to store it in a wrapper class first and, of course, unpack it later upon retrieving it. The combination of these factors made code working with collections less readable and more dangerous to boot.
Two biggest new features:
Generic types make it possible to have truly typesafe collections.
The introduction of autoboxing and unboxing of primitive types means that you can generally treat objects and primitives as equals as far as collections are concerned.
Java.util pachage:
Collection interface represents a container that holds other objects.
Map interface represents a group of key/value pairs.
java.util package (J2SE 5.0)
General Rules
ArrayList and LinkedList provide the array and linked list implementations of the List interface described earlier. ArrayList is satisfactory for most purposes but use LinkedList when you plan to do a lot of insertions or deletions at various points in the list.
HashSet and HashMap provide a good hash map implementation of the Set and Map interfaces. The LinkedHashSet and LinkedHashMap implementations combine the hash algorithm with a linked list that maintains insertion order of the elements. (Note that these linked collections are ordered, but not sorted collections.)
TreeSet and TreeMap maintain sorted collections using a tree data structure. In the case of TreeMap, it is the key values that are sorted. The sorting is accomplished by a comparator object. We'll discuss sorting later in this chapter.
Queue is implemented both by LinkedList (which implements both List and Queue) and PriorityQueue. A PriorityQueue's prioritization comes from a sorting order determined by a comparator supplied with its constructor. Elements that sort "least" or "lowest" have the highest priority. The various implementations of BlockingQueue mirror these for concurrency-aware queues.
Finally, IdentityHashMap is an alternate type of HashMap that uses object identity instead of object equality to determine which keys match which objects. Normally any two objects that test equal with equals( ) operate as the same key in a Map. With IdentityHashMap, only the original object instance retrieves the element.
We should also mention three specialized collections that we'll talk about later: EnumSet and EnumMap are specifically designed to work with Java enumerations. WeakHashMap uses weak references to cooperate with Java garbage collection.
Synchronized and Unsynchronized Collections
To create a synchronized versioin of any collection:
A threadsafe List:
List list = new ArrayList();
List syncList = Collections.synchronizedList(list);
java.util.Vector
java.util.Hashtable
Prior to java 5.0, the Collections Framework had two major drawbacks.
The collections were untyped and worked only with anonymous Objects instead of real types like Dates and Strings.This meant that you had to perform a type cast every time you took an object out of a collection. In theory, this broke Java's compile-time type safety.
The second problem was that, for practical reasons, collections could work only with objects and not with primitive types. This meant that any time you wanted to put a number or other primitive type into a collection you had to store it in a wrapper class first and, of course, unpack it later upon retrieving it. The combination of these factors made code working with collections less readable and more dangerous to boot.
Two biggest new features:
Generic types make it possible to have truly typesafe collections.
The introduction of autoboxing and unboxing of primitive types means that you can generally treat objects and primitives as equals as far as collections are concerned.
Java.util pachage:
Collection interface represents a container that holds other objects.
Map interface represents a group of key/value pairs.
java.util package (J2SE 5.0)
General Rules
ArrayList and LinkedList provide the array and linked list implementations of the List interface described earlier. ArrayList is satisfactory for most purposes but use LinkedList when you plan to do a lot of insertions or deletions at various points in the list.
HashSet and HashMap provide a good hash map implementation of the Set and Map interfaces. The LinkedHashSet and LinkedHashMap implementations combine the hash algorithm with a linked list that maintains insertion order of the elements. (Note that these linked collections are ordered, but not sorted collections.)
TreeSet and TreeMap maintain sorted collections using a tree data structure. In the case of TreeMap, it is the key values that are sorted. The sorting is accomplished by a comparator object. We'll discuss sorting later in this chapter.
Queue is implemented both by LinkedList (which implements both List and Queue) and PriorityQueue. A PriorityQueue's prioritization comes from a sorting order determined by a comparator supplied with its constructor. Elements that sort "least" or "lowest" have the highest priority. The various implementations of BlockingQueue mirror these for concurrency-aware queues.
Finally, IdentityHashMap is an alternate type of HashMap that uses object identity instead of object equality to determine which keys match which objects. Normally any two objects that test equal with equals( ) operate as the same key in a Map. With IdentityHashMap, only the original object instance retrieves the element.
We should also mention three specialized collections that we'll talk about later: EnumSet and EnumMap are specifically designed to work with Java enumerations. WeakHashMap uses weak references to cooperate with Java garbage collection.
Synchronized and Unsynchronized Collections
To create a synchronized versioin of any collection:
A threadsafe List:
List list = new ArrayList();
List syncList = Collections.synchronizedList(list);
Wednesday, May 9, 2007
Installing and deploying app for Axis 1.X
First of all, I have to say that it's a pain in the #@!$@# to deploy your class as webservices using Axis 1.x. Unless you have to do it, here is what I did.
Installing Axis
1. Copy webapps/axis directory from axis_unzip_folder/webapps/axis to web applications folder
2. Make sure the following jars are in the WEB-INF/lib folder
3. Make sure that web.xml and server-config.wsdd is in your WEB-INF folder
4. Evalutate installation with happyaxis.jsp
ref
Deploying application
1. We have a piece of code
2. We want to take theexisting code, wrap it up as a Web service, and then deploy it to the Apache Axis system.
3. Once we have a running service on the server side, we will create java stubs that allow up to communicate with the service, only requiring the WSDL.
Here are the steps:
1. Java2WSDL: Generate the WSDL file for the given interface.
To run ant tasks for java2wsdl, make sure the following jars are in the classpath
1. axis.jar
2. axis-ant.jar
3. jaxrpc.jar
4. log4j.jar
5. saaj.jar
6. wsdl4j.jar
2. WSDL2Java: Generate the server side wrapper code, and stubs for easy client access.
Java stub classes/interfaces will be generated according to the wsdl specified.
3. classinterfaceSoapBindingImpl: Fill in wrapper to call the existing code.
4. Deploy the service to Apache Axis
Deploy the war folder/file onto application server
Run: java org.apache.axis.client.AdminClient
-p"7003" -h"localhost" -s"axis-test/servlet/AxisServlet" war\hello\deploy.wsdd
5. Write a client that uses the generated stubs, to easily access the web service.
HelloWorldService service = new HelloWorldServiceLocator();
HelloWorld hw = service.gethello();
Ref
Installing Axis
1. Copy webapps/axis directory from axis_unzip_folder/webapps/axis to web applications folder
2. Make sure the following jars are in the WEB-INF/lib folder
- axis.jar
- axis-ant.jar
- commons-discovery-0.2.jar
- commons-logging-1.0.4.jar
- jaxrpc.jar
- log4j-1.2.8.jar
- log4j.properties
- saaj.jar
- wsdl4j-1.5.1.jar
3. Make sure that web.xml and server-config.wsdd is in your WEB-INF folder
4. Evalutate installation with happyaxis.jsp
ref
Deploying application
1. We have a piece of code
2. We want to take theexisting code, wrap it up as a Web service, and then deploy it to the Apache Axis system.
3. Once we have a running service on the server side, we will create java stubs that allow up to communicate with the service, only requiring the WSDL.
Here are the steps:
1. Java2WSDL: Generate the WSDL file for the given interface.
To run ant tasks for java2wsdl, make sure the following jars are in the classpath
1. axis.jar
2. axis-ant.jar
3. jaxrpc.jar
4. log4j.jar
5. saaj.jar
6. wsdl4j.jar
2. WSDL2Java: Generate the server side wrapper code, and stubs for easy client access.
Java stub classes/interfaces will be generated according to the wsdl specified.
3. classinterfaceSoapBindingImpl: Fill in wrapper to call the existing code.
4. Deploy the service to Apache Axis
Deploy the war folder/file onto application server
Run: java org.apache.axis.client.AdminClient
-p"7003" -h"localhost" -s"axis-test/servlet/AxisServlet" war\hello\deploy.wsdd
5. Write a client that uses the generated stubs, to easily access the web service.
HelloWorldService service = new HelloWorldServiceLocator();
HelloWorld hw = service.gethello();
Ref
Sunday, May 6, 2007
Axis
Axis is all about processing Messages
When the central Axis processing logic runs, a series of Handlers are each invoked. The particular order is determined by two factors:
The object passed to each Handler invocation is a MessageContext
MessageContext contains
Message path on the Server
Transport -> Global -> Service
Message path on the client
Client app -> Service -> Global -> Transport
Handlers are either transport-specific, service-specific, or global. The handlers of each of these three different kinds are combined together into Chains. So the overall sequence of Handlers comprises three Chains: transport, global, and service.
A Chain is a composite handler. It aggregates a collection of Handlers as well as implementing the Handler interface.
Axis supports scoping service objects (the actual Java objects which implement your methods) three ways. "Request" scope, the default, will create a new object each time a SOAP request comes in for your service. "Application" scope will create a singleton shared object to service all requests. "Session" scope will create a new object for each session-enabled client who accesses your service. To specify the scope option, you add a to your service like this (where "value" is request, session, or application):
<service name="MyService"... >
<parameter name="scope" value="value"/ >
...
</service >
Message Processing
A message is processed by passing through the appropriate Chains. A message context is used to pass the message and associated environment through the sequence of Handlers. The model is that Axis Chains are constructed offline by having Handlers added to them one at a time.
A Targeted Chain is a special kind of chain which may have any or all of: a request Handler, a pivot handler, and a response Handler.
A service is a special kind of Targeted Chain in which the pivot Handler is known as a "provider".
Axis has an abstract AxisEngine class with two concrete subclasses: AxisClient drives the client side handler chains and AxisServer drives the server side handler chains.
The EngineConfiguration interface is the means of configuring the Handler factories and global options of an engine instance. An instance of a concrete implementation of EngineConfiguration must be passed to the engine when it is created and the engine must be notified if the EngineConfiguration contents are modified.
WSDD is an XML grammar for deployment descriptors which are used to statically configure Axis engines.
Each handler needs configuration in terms of
Exceptions
RemoteExceptions map to SOAP Faults
Exceptions are represented as wsdl:fault elements
Axis will only send objects for which there is a registered Axis serializer.
WSDL2Java: Building stubs, skeletons, and data types from WSDL
Client-side bindings
% java org.apache.axis.wsdl.WSDL2Java (WSDL-file_URL)
type mapping
ref
When the central Axis processing logic runs, a series of Handlers are each invoked. The particular order is determined by two factors:
- Deployment Configuration
- Client Engine or Server Engine
The object passed to each Handler invocation is a MessageContext
MessageContext contains
- a "request" message
- a "response" message
- a bag of properties
Message path on the Server
Transport -> Global -> Service
Message path on the client
Client app -> Service -> Global -> Transport
Handlers are either transport-specific, service-specific, or global. The handlers of each of these three different kinds are combined together into Chains. So the overall sequence of Handlers comprises three Chains: transport, global, and service.
A Chain is a composite handler. It aggregates a collection of Handlers as well as implementing the Handler interface.
Axis supports scoping service objects (the actual Java objects which implement your methods) three ways. "Request" scope, the default, will create a new object each time a SOAP request comes in for your service. "Application" scope will create a singleton shared object to service all requests. "Session" scope will create a new object for each session-enabled client who accesses your service. To specify the scope option, you add a
<service name="MyService"... >
<parameter name="scope" value="value"/ >
...
</service >
Message Processing
A message is processed by passing through the appropriate Chains. A message context is used to pass the message and associated environment through the sequence of Handlers. The model is that Axis Chains are constructed offline by having Handlers added to them one at a time.
A Targeted Chain is a special kind of chain which may have any or all of: a request Handler, a pivot handler, and a response Handler.
A service is a special kind of Targeted Chain in which the pivot Handler is known as a "provider".
Axis has an abstract AxisEngine class with two concrete subclasses: AxisClient drives the client side handler chains and AxisServer drives the server side handler chains.
The EngineConfiguration interface is the means of configuring the Handler factories and global options of an engine instance. An instance of a concrete implementation of EngineConfiguration must be passed to the engine when it is created and the engine must be notified if the EngineConfiguration contents are modified.
WSDD is an XML grammar for deployment descriptors which are used to statically configure Axis engines.
Each handler needs configuration in terms of
the concrete class name of a factory for the Handler
a set of options for the handler
a lifecycle scope value which determins the scope of sharing of instances of the Handler.
Exceptions
RemoteExceptions map to SOAP Faults
Exceptions are represented as wsdl:fault elements
Axis will only send objects for which there is a registered Axis serializer.
WSDL2Java: Building stubs, skeletons, and data types from WSDL
Client-side bindings
% java org.apache.axis.wsdl.WSDL2Java (WSDL-file_URL)
type mapping
ref
Subscribe to:
Posts (Atom)