04 May 2012

Behavioral Design Pattern –  Chain of Responsibility


Behavioral patterns are concerned with the interaction and responsibility of objects. They help make complex behavior manageable by specifying the responsibilities of objects and the ways they communicate with each other.

The following Behavioral patterns are described by GoF:
  • Chain of Responsibility
  • Command
  • Interpreter
  • Iterator
  • Mediator
  • Memento
  • Observer
  • State
  • Strategy
  • Template Method
  • Visitor

Chain of Responsibility 

The Chain of Responsibility pattern’s intent is to avoid coupling the sender of a request to its receiver by giving multiple objects a chance to handle the request. The request is passed along the chain of receiving objects until an object processes it. shows the UML.

The Chain of Responsibility pattern’s intent is to avoid coupling the sender of a request to its receiver by giving multiple objects a chance to handle the request. The request is passed along the chain of receiving objects until an object processes it. shows the UML.



Figure  UML for the Chain of Responsibility pattern
Benefits  Following are the benefits of using the Chain of Responsibility pattern:
  • It reduces coupling.
  • It adds flexibility when assigning responsibilities to objects.
  • It allows a set of classes to act as one; events produced in one class can be sent to other handler classes within the composition.
Applicable Scenarios  The following scenarios are most appropriate for the Chain of Responsibility pattern:
  • More than one object can handle a request and the handler is unknown.
  • A request is to be issued to one of several objects and the receiver is not specified explicitly.
  • The set of objects able to handle the request is to be specified dynamically.
J2EE Technology Feature  The J2EE technology feature associated with the Chain of Responsibility pattern is RequestDispatcher in the servlet/JSP API.

Example Code  The following example Java code demonstrates the Chain of Responsibility pattern:



package j2ee.architect.ChainOfResponsibility;

public class ChainOfResponsibilityPattern {
public static void main(String[] args) {
System.out.println("Chain Of Responsibility Pattern Demonstration.");
System.out.println("———————————————————————");
try {
// Create Equity Order request.
System.out.println("Creating Equity Order request.");
Request equityOrderRequest = new Request(Request.EQUITY_ORDER);
// Create Bond Order request.
System.out.println("Creating Bond Order request.");
Request bondOrderRequest = new Request(Request.BOND_ORDER);
// Create a request handler.
System.out.println("Creating 1st handler.");
HandlerIF handler = new ConcreteHandler1();
// Process the Equity Order.
System.out.println("Calling 1st handler with Equity Order.");
handler.processRequest(equityOrderRequest);
// Process the Bond Order.
System.out.println("Calling 1st handler with Bond Order");
handler.processRequest(bondOrderRequest);
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println();
}
}

package j2ee.architect.ChainOfResponsibility;
public class ConcreteHandler1 implements HandlerIF {
public void processRequest(Request parm) {
// Start the processing chain here...
switch (parm.getType()) {
case Request.EQUITY_ORDER: // This object processes equity orders
handleIt(parm);          // so call the function to handle it.
break;
case Request.BOND_ORDER:   // Another object processes bond orders so
System.out.println("Creating 2nd handler."); // pass request along.
new ConcreteHandler2().processRequest(parm);
break;
}
}
private void handleIt(Request parm) {
System.out.println("ConcreteHandler1 has handled the processing.");
}
}
package j2ee.architect.ChainOfResponsibility;
public class ConcreteHandler2 implements HandlerIF {
public void processRequest(Request parm) {
// You could add on to the processing chain here...
handleIt(parm);
}
private void handleIt(Request parm) {
System.out.println("ConcreteHandler2 has handled the processing.");
}
}
package j2ee.architect.ChainOfResponsibility;
public interface HandlerIF {
public void processRequest(Request request);
}
package j2ee.architect.ChainOfResponsibility;
public class Request {
// The universe of known requests that can be handled.
public final static int EQUITY_ORDER = 100;
public final static int BOND_ORDER   = 200;
// This objects type of request.
private int type;
public Request(int parm) throws Exception {
// Validate the request type with the known universe.
if ((parm == EQUITY_ORDER) || (parm == BOND_ORDER))
// Store this request type.
this.type = parm;
else
throw new Exception("Unknown Request type "+parm+".");
}
public int getType() {
return type;
}
}


30 April 2012

Enterprise Service Bus and SOA



SOA Principles :

1. LOOSE COUPLING

Loose coupling is a principle by which the consumer and service are insulated from changes in underlying technology and behavior. In some manner, the loose coupling principle describes a logical separation of concerns. That is, the consumers in our SOA are intentionally separated from direct or physical connection to services. The intent is to protect the individual integrity of each SOA consumer and SOA service and to avoid physical dependencies between them (see Figure 2.1).
When this principle is applied to the design of our services and the service interface, we can mitigate the impact of change. The most common example is an SOA service that has been previously implemented and deployed into the ESB. In this example, a number of consuming applications are successfully using the service. As new consumers find the service, they may also require additional functionality and data not defined to this service. If the service were tightly coupled with each of the previous consumers, the ability to add new functionality to the service would be significantly limited. When tightly coupled, those previously existing consumers would likely be affected by changes to the service. Alternatively, when consumers and services are loosely coupled, there are techniques that can be applied to help mitigate the impact of change to existing consumers of a service. Previous consumers are then unaware and generally unaffected by new additions to the service functionality.
To comply with the loose coupling principle, consumers and services do not communicate directly. As we learned in Chapter 1consumers and services communicate via messaging. Using a message to exchange requests and replies avoids any direct technical connections between consumers and services. In addition to messaging, there are other service interface design techniques that can be applied to further limit the degree of coupling between consumers and the service.
Messages exchanged between consumers and services are realizations of the service interface. In the case of a Web service, the service interface is defined by the combination of a Web Service Definition Language artifact (WSDL) and an XML Schema definition (XSD) as its referenced metadata. These two types of interface artifacts (WSDL and XML Schemas) are the foundation of any Web service. The design and development of these two interface artifacts are a focus of the loose coupling principle. Other types of services can use other interface definitions and artifacts, but the same principle of loose coupling can still be applied.
The role of the ESB in SOA
In order to implement an SOA, both applications and infrastructure must support the SOA principles. Enabling applications involves the creation of service interfaces to existing or new functions, either directly or through the use of adapters. Enabling the infrastructure at the most basic level involves the provision of capability to route and transport service requests to the correct service provider. The role of the Enterprise Service Bus is, in part, simply to enable the infrastructure in this way.
The true value of the Enterprise Service Bus concept, however, is to enable the infrastructure for SOA in a way that reflects the needs of today’s enterprise: to provide suitable service levels and manageability, and to operate and integrate in a heterogeneous environment. The implications of these requirements go beyond basic routing and transport capability, and they are described in The Enterprise Service Bus Capability Model in 4.3, “A capability model for the Enterprise Service Bus” on page 82.
The ESB should enable the substitution of one service implementation by another with no effect to the clients of that service. This requires both the service interfaces that are specified by SOA and that the ESB allows client code to invoke services in a manner that is independent of the service location and communication protocol that is involved.


The ESB supports multiple integration paradigms

In order to fully support the variety of interaction patterns that are required in a
comprehensive SOA (for example, request / response, publish / subscribe, events), the Enterprise Service Bus must support in one infrastructure the three major styles of Enterprise Integration:

  • Service-oriented architectures in which applications communicate through reusable services with well-defined, explicit interfaces. Service-oriented interactions leverage underlying messaging and event communication models. 
  • Message-driven architectures in which applications send messages through the ESB to receiving applications. 
  • Event-driven architectures in which applications generate and consume messages independently of one another.

The ESB does this while providing additional capabilities to mediate or transform
service messages and interactions, enabling a wide variety of behaviors and supporting the various models of coupling interaction that are described in 3.2.1, “Coupling and decoupling of aspects of service interactions.

shows a high-level view of the Enterprise Service Bus.



25 April 2012

What Types of Objects Can Be Clustered?


A clustered application or application component is one that is available on multiple WebLogic Server instances in a cluster. If an object is clustered, failover and load balancing for that object is available. Deploy objects homogeneously—to every server instance in your cluster—to simplify cluster administration, maintenance, and troubleshooting.
Web applications can consist of different types of objects, including Enterprise Java Beans (EJBs), servlets, and Java Server Pages (JSPs). Each object type has a unique set of behaviors related to control, invocation, and how it functions within an application. For this reason, the methods that WebLogic Server uses to support clustering—and hence to provide load balancing and failover—can vary for different types of objects. The following types of objects can be clustered in a WebLogic Server deployment:
  • Servlets
  • JSPs
  • EJBs
  • Remote Method Invocation (RMI) objects
  • Java Messaging Service (JMS) destinations
  • Java Database Connectivity (JDBC) connections
Different object types can have certain behaviors in common. When this is the case, the clustering support and implementation considerations for those similar object types may be same. In the sections that follow, explanations and instructions for the following types of objects are generally combined:
  • Servlets and JSPs
  • EJBs and RMI objects
The sections that follow briefly describe the clustering, failover, and load balancing support that WebLogic Server provides for different types of objects.

22 April 2012

Regular Expressions in Java


Java 4 (JDK 1.4) and later have comprehensive support for regular expressions through the standard java.util.regex package. Because Java lacked a regex package for so long, there are also many 3rd party regex packages available for Java. I will only discuss Sun’s regex library that is now part of the JDK. Its quality is excellent, better than most of the 3rd party packages. Unless you need to support older versions of the JDK, the java.util.regex package is the way to go.

Java 5 and 6 use the same regular expression flavor (with a few minor fixes), and provide the same regular expression classes. They add a few advanced functions not discussed on this page.

Quick Regex Methods of The String Class

The Java String class has several methods that allow you to perform an operation using a regular expression on that string in a minimal amount of code. The downside is that you cannot specify options such as "case insensitive" or "dot matches newline". For performance reasons, you should also not use these methods if you will be using the same regular expression often.

myString.matches("regex") returns true or false depending whether the string can be matched entirely by the regular expression. It is important to remember that String.matches() only returns true if the entire string can be matched. In other words: "regex" is applied as if you had written "^regex$" with start and end of string anchors. This is different from most other regex libraries, where the "quick match test" method returns true if the regex can be matched anywhere in the string. If myString is abc then myString.matches("bc") returns false. bc matches abc, but ^bc$ (which is really being used here) does not.
myString.replaceAll("regex", "replacement") replaces all regex matches inside the string with the replacement string you specified. No surprises here. All parts of the string that match the regex are replaced. You can use the contents of capturing parentheses in the replacement text via $1, $2, $3, etc. $0 (dollar zero) inserts the entire regex match. $12 is replaced with the 12th backreference if it exists, or with the 1st backreference followed by the literal "2" if there are less than 12 backreferences. If there are 12 or more backreferences, it is not possible to insert the first backreference immediately followed by the literal "2" in the replacement text.

In the replacement text, a dollar sign not followed by a digit causes an IllegalArgumentException to be thrown. If there are less than 9 backreferences, a dollar sign followed by a digit greater than the number of backreferences throws an IndexOutOfBoundsException. So be careful if the replacement string is a user-specified string. To insert a dollar sign as literal text, use \$ in the replacement text. When coding the replacement text as a literal string in your source code, remember that the backslash itself must be escaped too: "\\$".

myString.split("regex") splits the string at each regex match. The method returns an array of strings where each element is a part of the original string between two regex matches. The matches themselves are not included in the array. Use myString.split("regex", n) to get an array containing at most n items. The result is that the string is split at most n-1 times. The last item in the string is the unsplit remainder of the original string.

Using The Pattern Class

In Java, you compile a regular expression by using the Pattern.compile() class factory. This factory returns an object of type Pattern. E.g.: Pattern myPattern = Pattern.compile("regex"); You can specify certain options as an optional second parameter. Pattern.compile("regex", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE) makes the regex case insensitive for US ASCII characters, causes the dot to match line breaks and causes the start and end of string anchors to match at embedded line breaks as well. When working with Unicode strings, specify Pattern.UNICODE_CASE if you want to make the regex case insensitive for all characters in all languages. You should always specify Pattern.CANON_EQ to ignore differences in Unicode encodings, unless you are sure your strings contain only US ASCII characters and you want to increase performance.

If you will be using the same regular expression often in your source code, you should create a Pattern object to increase performance. Creating a Pattern object also allows you to pass matching options as a second parameter to the Pattern.compile() class factory. If you use one of the String methods above, the only way to specify options is to embed mode modifier into the regex. Putting (?i) at the start of the regex makes it case insensitive. (?m) is the equivalent of Pattern.MULTILINE, (?s) equals Pattern.DOTALL and (?u) is the same as Pattern.UNICODE_CASE. Unfortunately, Pattern.CANON_EQ does not have an embedded mode modifier equivalent.

Use myPattern.split("subject") to split the subject string using the compiled regular expression. This call has exactly the same results as myString.split("regex"). The difference is that the former is faster since the regex was already compiled.

Using The Matcher Class

Except for splitting a string (see previous paragraph), you need to create a Matcher object from the Pattern object. The Matcher will do the actual work. The advantage of having two separate classes is that you can create many Matcher objects from a single Pattern object, and thus apply the regular expression to many subject strings simultaneously.

To create a Matcher object, simply call Pattern.matcher() like this: myMatcher = Pattern.matcher("subject"). If you already created a Matcher object from the same pattern, call myMatcher.reset("newsubject") instead of creating a new matcher object, for reduced garbage and increased performance. Either way, myMatcher is now ready for duty.

To find the first match of the regex in the subject string, call myMatcher.find(). To find the next match, call myMatcher.find() again. When myMatcher.find() returns false, indicating there are no further matches, the next call to myMatcher.find() will find the first match again. The Matcher is automatically reset to the start of the string when find() fails.

The Matcher object holds the results of the last match. Call its methods start(), end() and group() to get details about the entire regex match and the matches between capturing parentheses. Each of these methods accepts a single int parameter indicating the number of the backreference. Omit the parameter to get information about the entire regex match. start() is the index of the first character in the match. end() is the index of the first character after the match. Both are relative to the start of the subject string. So the length of the match is end() – start(). group() returns the string matched by the regular expression or pair of capturing parentheses.

myMatcher.replaceAll("replacement") has exactly the same results as myString.replaceAll("regex", "replacement"). Again, the difference is speed.

The Matcher class allows you to do a search-and-replace and compute the replacement text for each regex match in your own code. You can do this with the appendReplacement() and appendTail() Here is how:
StringBuffer myStringBuffer = new StringBuffer();

myMatcher = myPattern.matcher("subject");

while (myMatcher.find()) {
    if (checkIfThisMatchShouldBeReplaced()) {
        myMatcher.appendReplacement(myStringBuffer, computeReplacementString());
    }
}

myMatcher.appendTail(myStringBuffer);
Obviously, checkIfThisMatchShouldBeReplaced() and computeReplacementString() are placeholders for methods that you supply. The first returns true or false indicating if a replacement should be made at all. Note that skipping replacements is way faster than replacing a match with exactly the same text as was matched.computeReplacementString() returns the actual replacement string.
Regular Expressions, Literal Strings and Backslashes
In literal Java strings the backslash is an escape character. The literal string "\\" is a single backslash. In regular expressions, the backslash is also an escape character. The regular expression \\ matches a single backslash. This regular expression as a Java string, becomes "\\\\". That’s right: 4 backslashes to match a single one.

The regex \w matches a word character. As a Java string, this is written as "\\w".
The same backslash-mess occurs when providing replacement strings for methods like String.replaceAll() as literal Java strings in your Java code. In the replacement text, a dollar sign must be encoded as \$ and a backslash as \\ when you want to replace the regex match with an actual dollar sign or backslash. However, backslashes must also be escaped in literal Java strings. So a single dollar sign in the replacement text becomes "\\$" when written as a literal Java string. The single backslash becomes "\\\\". Right again: 4 backslashes to insert a single one.

Tomcat Class Loading


   
 
      Bootstrap
          |
       System
          |
       Common
      /      \
 Catalina   Shared
             /   \
        Webapp1  Webapp2 ...
 
   

Class Loader Definitions

As indicated in the diagram above, Tomcat 4 creates the following class loaders as it is initialized:
  • Bootstrap - This class loader contains the basic runtime classes provided by the Java Virtual Machine, plus any classes from JAR files present in the System Extensions directory ($JAVA_HOME/jre/lib/ext). NOTE - Some JVMs may implement this as more than one class loader, or it may not be visible (as a class loader) at all.
  • System - This class loader is normally initialized from the contents of the CLASSPATH environment variable. All such classes are visible to both Tomcat internal classes, and to web applications. However, the standard Tomcat 4 startup scripts ($CATALINA_HOME/bin/catalina.sh or %CATALINA_HOME%\bin\catalina.bat) totally ignore the contents of the CLASSPATH environment variable itself, and instead build the System class loader from the following repositories:
    • $CATALINA_HOME/bin/bootstrap.jar - Contains the main() method that is used to initialize the Tomcat 4 server, and the class loader implementation classes it depends on.
    • $JAVA_HOME/lib/tools.jar - Contains the "javac" compiler used to convert JSP pages into servlet classes.
  • Common - This class loader contains additional classes that are made visible to both Tomcat internal classes and to all web applications. Normally, application classes should NOT be placed here. All unpacked classes and resources in $CATALINA_HOME/common/classes, as well as classes and resources in JAR files under the $CATALINA_HOME/commons/endorsed and $CATALINA_HOME/common/lib directories, are made visible through this class loader. By default, that includes the following:
    • jndi.jar - The Java Naming and Directory Interface API classes (loaded ONLY on a JDK 1.2 system, because they are included automatically on JDK 1.3 and later).
    • naming-common.jar - The JNDI implementation used by Tomcat 4 to represent in-memory naming contexts.
    • naming-resources.jar - The specialized JNDI naming context implementation used to represent the static resources of a web application.
    • servlet.jar - The Servlet and JSP API classes.
    • xerces.jar - The XML parser that is visible by default to Tomcat internal classes and to web applications. This can be overridden, for a particular web application, by including your desired parser in /WEB-INF/lib.
  • Catalina - This class loader is initialized to include all classes and resources required to implement Tomcat 4 itself. These classes and resources are TOTALLY invisible to web applications. All unpacked classes and resources in$CATALINA_HOME/server/classes, as well as classes and resources in JAR files under $CATALINA_HOME/server/lib, are made visible through this class loader. By default, that includes the following:
    • catalina.jar - Implementation of the Catalina servlet container portion of Tomcat 4.
    • jakarta-regexp-X.Y.jar - The binary distribution of the Jakarta Regexp regular expression processing library, used in the implementation of request filters.
    • servlets-xxxxx.jar - The classes associated with each internal servlet that provides part of Tomcat's functionality. These are separated so that they can be completely removed if the corresponding service is not required, or they can be subject to specialized security manager permissions.
    • tomcat-coyote.jar - Coyote connector for Tomcat 4.
    • tomcat-http11.jar - Standalone Java HTTP/1.1 connector.
    • tomcat-jk.jar - Classes for the Java portion of the JK web server connector, which allows Tomcat to run behind web servers such as Apache and iPlanet iAS and iWS.
    • tomcat-jk2.jar - Classes for the Java portion of the JK 2 web server connector, which allows Tomcat to run behind web servers such as Apache and iPlanet iAS and iWS.
    • tomcat-util.jar - Utility classes required by some Tomcat connectors.
    • tomcat-warp.jar - Classes for the Java portion of the Webapp web server connector, using the WARP protocol which allows Tomcat to run behind the Apache HTTPD web server (1.3 and 2.0).
  • Shared - This class loader is the place to put classes and resources that you wish to share across ALL web applications (unless Tomcat internal classes also need access, in which case you should put them in the Common class loader instead). All unpacked classes and resources in $CATALINA_BASE/shared/classes, as well as classes and resources in JAR files under $CATALINA_BASE/shared/lib, are made visible through this class loader. By default, that includes the following:
    • jasper-compiler.jar - The page compiler classes required to convert JSP source pages into executable servlets and compile them.
    • jasper-runtime.jar - The runtime support classes required to execute JSP pages that have already been translated into Java servlets and then compiled.
    • naming-factory.jar - JNDI object factories for resources supported by the default JNDI naming context provided to web applications.
  • WebappX - A class loader is created for each web application that is deployed in a single Tomcat 4 instance. All unpacked classes and resources in the /WEB-INF/classes directory of your web application archive, plus classes and resources in JAR files under the /WEB-INF/lib directory of your web application archive, are made visible to the containing web application, but to no others.
As mentioned above, the web application class loader diverges from the default Java 2 delegation model (in accordance with the recommendations in the Servlet Specification, version 2.3, section 9.6). When a request to load a class from the web application's WebappX class loader is processed, this class loader will look in the local repositories first, instead of delegating before looking. All other class loaders in Tomcat 4 follow the usual delegation pattern.Therefore, from the perspective of a web application, class or resource loading looks in the following repositories, in this order:
  • /WEB-INF/classes of your web application
  • /WEB-INF/lib/*.jar of your web application
  • Bootstrap classes of your JVM
  • System class loader classses (described above)
  • $CATALINA_HOME/common/classes
  • $CATALINA_HOME/common/endorsed/*.jar
  • $CATALINA_HOME/common/lib/*.jar
  • $CATALINA_BASE/shared/classes
  • $CATALINA_BASE/shared/lib/*.jar

Immutable class in Java


Immutable class is a class which once created, it’s contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String class
To create an immutable class following steps should be followed:
  1. Create a final class.
  2. Set the values of properties using constructor only.
  3. Make the properties of the class final and private
  4. Do not provide any setters for these properties.
  5. If the instance fields include references to mutable objects, don’t allow those objects to be changed:
    1. Don’t provide methods that modify the mutable objects.
    2. Don’t share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
E.g.

public final class FinalPersonClass {
private final String name;
private final int age;
public FinalPersonClass(final String name, final int age) {
super();
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}

Java Monitors


One of the strengths of the Java programming language is its support for multithreading at the language level. Much of this support centers on synchronization: coordinating activities and data access among multiple threads. The mechanism that Java uses to support synchronization is the monitor. This chapter describes monitors and shows how they are used by the Java virtual machine. It describes how one aspect of monitors, the locking and unlocking of data, is supported in the instruction set.

Java's monitor supports two kinds of thread synchronization: mutual exclusion and cooperation. Mutual exclusion, which is supported in the Java virtual machine via object locks, enables multiple threads to independently work on shared data without interfering with each other. Cooperation, which is supported in the Java virtual machine via the wait and notify methods of class Object, enables threads to work together towards a common goal.

A monitor is like a building that contains one special room that can be occupied by only one thread at a time. The room usually contains some data. From the time a thread enters this room to the time it leaves, it has exclusive access to any data in the room. Entering the monitor building is called "entering the monitor." Entering the special room inside the building is called "acquiring the monitor." Occupying the room is called "owning the monitor," and leaving the room is called "releasing the monitor." Leaving the entire building is called "exiting the monitor."

In addition to being associated with a bit of data, a monitor is associated with one or more bits of code, which in this book will be called monitor regions. A monitor region is code that needs to be executed as one indivisible operation with respect to a particular monitor. In other words, one thread must be able to execute a monitor region from beginning to end without another thread concurrently executing a monitor region of the same monitor. A monitor enforces this one-thread-at-a-time execution of its monitor regions. The only way a thread can enter a monitor is by arriving at the beginning of one of the monitor regions associated with that monitor. The only way a thread can move forward and execute the monitor region is by acquiring the monitor.

When a thread arrives at the beginning of a monitor region, it is placed into an entry set for the associated monitor. The entry set is like the front hallway of the monitor building. If no other thread is waiting in the entry set and no other thread currently owns the monitor, the thread acquires the monitor and continues executing the monitor region. When the thread finishes executing the monitor region, it exits (and releases) the monitor.

If a thread arrives at the beginning of a monitor region that is protected by a monitor already owned by another thread, the newly arrived thread must wait in the entry set. When the current owner exits the monitor, the newly arrived thread must compete with any other threads also waiting in the entry set. Only one thread will win the competition and acquire the monitor.

The first kind of synchronization listed above, mutual exclusion, refers to the mutually exclusive execution of monitor regions by multiple threads. At any one time, only one thread can be executing a monitor region of a particular monitor. In general, mutual exclusion is important only when multiple threads are sharing data or some other resource. If two threads are not working with any common data or resource, they usually can't interfere with each other and needn't execute in a mutually exclusive way. On a Java virtual machine implementation that doesn't time slice, however, a higher priority thread that is never blocked will interfere with any lower priority threads, even if none of the threads share data. The higher priority thread will monopolize the CPU at the expense of the lower priority threads. Lower priority threads will never get any CPU time. In such a case, a monitor that protects no data may be used to orchestrate these threads to ensure all threads get some CPU time. Nevertheless, in most cases a monitor protects data that is accessed through the monitor region code. In cases where the data can be accessed only through the monitor regions, the monitor enforces mutually exclusive access to that data.
The other kind of synchronization listed above as supported by monitors is cooperation. Whereas mutual exclusion helps keep threads from interfering with one another while sharing data, cooperation helps threads to work together towards some common goal.

Cooperation is important when one thread needs some data to be in a particular state and another thread 
is responsible for getting the data into that state. For example, one thread, a "read thread," may be reading data from a buffer that another thread, a "write thread," is filling. The read thread needs the buffer to be in a "not empty" state before it can read any data out of the buffer. If the read thread discovers that the buffer is empty, it must wait. The write thread is responsible for filling the buffer with data. Once the write thread has done some more writing, the read thread can do some more reading.
The form of monitor used by the Java virtual machine is called a "Wait and Notify" monitor. (It is also sometimes called a "Signal and Continue" monitor.) In this kind of monitor, a thread that currently owns the monitor can suspend itself inside the monitor by executing a wait command. When a thread executes a wait, it releases the monitor and enters a wait set. The thread will stay suspended in the wait set until some time after another thread executes a notify command inside the monitor. When a thread executes a notify, it continues to own the monitor until it releases the monitor of its own accord, either by executing a wait or by completing the monitor region. After the notifying thread has released the monitor, the waiting thread will be resurrected and will reacquire the monitor.

The kind of monitor used in the Java virtual machine is sometimes called a Signal and Continue monitor because after a thread does a notify (the signal) it retains ownership of the monitor and continues executing the monitor region (the continue). At some later time, the notifying thread releases the monitor and a waiting thread is resurrected. Presumably, the waiting thread suspended itself because the data protected by the monitor wasn't in a state that would allow the thread to continue doing useful work. Also, the notifying thread presumably executed the notify command after it had placed the data protected by the monitor into the state desired by the waiting thread. But because the notifying thread continued, it may have altered the state after the notify such that the waiting thread still can't do useful work. Alternatively, a third thread may have acquired the monitor after the notifying thread released it but before the waiting thread acquired it, and the third thread may have changed the state of the protected data. As a result, a notify must often be considered by waiting threads merely as a hint that the desired state may exist. Each time a waiting thread is resurrected, it may need to check the state again to determine whether it can move forward and do useful work. If it finds the data still isn't in the desired state, the thread could execute another wait or give up and exit the monitor.

As an example, consider once again the scenario described above that involves a buffer, a read thread, and a write thread. Assume the buffer is protected by a monitor. When a read thread enters the monitor that protects the buffer, it checks to see if the buffer is empty. If the buffer is not empty, the read thread reads (and removes) some data from the buffer. Satisfied, it exits the monitor. On the other hand, if the buffer is empty, the read thread executes a wait command. As soon as it executes the wait, the read thread is suspended and placed into the monitor's wait set. In the process, the read thread releases the monitor, which becomes available to other threads. At some later time, the write thread enters the monitor, writes some data into the buffer, executes a notify, and exits the monitor. When the write thread executes the notify, the read thread is marked for eventual resurrection. After the write thread has exited the monitor, the read thread is resurrected as the owner of the monitor. If there is any chance that some other thread has come along and consumed the data left by the write thread, the read thread must explicitly check to make sure the buffer is not empty. If there is no chance that any other thread has consumed the data, then the read thread can just assume the data exists. The read thread reads some data from the buffer and exits the monitor.

A graphical depiction of the kind of monitor used by a Java virtual machine is shown in Figure 20-1. This figure shows the monitor as three rectangles. In the center, a large rectangle contains a single thread, the monitor's owner. On the left, a small rectangle contains the entry set. On the right, another small rectangle contains the wait set. Active threads are shown as dark gray circles. Suspended threads are shown as light gray circles.

Figure 20-1 also shows several numbered doors that threads must "pass through" to interact with the monitor. When a thread arrives at the start of a monitor region, it enters the monitor via the leftmost door, door number one, and finds itself in the rectangle that houses the entry set. If no thread currently owns the monitor and no other threads are waiting in the entry set, the thread passes immediately through the next door, door number two, and becomes the owner of the monitor. As the monitor owner, the thread continues executing the monitor region. If, on the other hand, there is another thread currently claiming ownership of the monitor, the newly arrived thread must wait in the entry set, possibly along with other threads already waiting there. The newly arrived thread is blocked and therefore doesn't execute any further into the monitor region.

Figure 20-1 shows three threads suspended in the entry set and four threads suspended in the wait set. These threads will remain where they are until the current owner of the monitor--the active thread--releases the monitor. The active thread can release the monitor in either of two ways: it can complete the monitor region it is executing or it can execute a wait command. If it completes the monitor region, it exits the monitor via the door at the bottom of the central rectangle, door number five. If it executes a wait command, it releases the monitor as it travels through door number three, the door to the wait set.
If the former owner did not execute a notify before it released the monitor (and none of the waiting threads were previously notified and were waiting to be resurrected), then only the threads in the entry set will compete to acquire the monitor. If the former owner did execute a notify, then the entry set threads will have to compete with one or more threads from the wait set. If a thread from the entry set wins the competition, it passes through door number two and becomes the new owner of the monitor. If a thread from the wait set wins the competition, it exits the wait set and reacquires the monitor as it passes through door number four. Note that doors three and four are the only ways a thread can enter or exit the wait set. A thread can only execute a wait command if it currently owns the monitor, and it can't leave the wait set without automatically becoming again the owner of the monitor.

In the Java virtual machine, threads can optionally specify a timeout when they execute a wait command. If a thread does specify a timeout, and no other thread executes a notify before the timeout expires, the waiting thread in effect receives an automatic notify from the virtual machine. After the timeout expires, the waiting thread will be resurrected even if no other thread has executed an explicit notify.
The Java virtual machine offers two kinds of notify commands: "notify" and "notify all." A notify command selects one thread arbitrarily from the wait set and marks it for eventual resurrection. A notify all command marks all threads currently in the wait set for eventual resurrection.
To a great extent, the manner in which a Java virtual machine implementation selects the next thread from the wait or entry sets is a decision of individual implementation designers. For example, implementation designers can decide how to select: o a thread from the wait set given a notify command o the order to resurrect threads from the wait set given a notify all command o the order to allow threads from the entry set to acquire the monitor o how to choose between threads suspended in the wait set versus the entry set after a notify command You might think it would make sense to implement entry set and wait sets as first-in-first-out (FIFO) queues, so that the thread that waits the longest will be the first chosen to acquire the monitor. Alternatively, it might make sense to have ten FIFO queues, one for each priority a thread can have inside the Java virtual machine. The virtual machine could then choose the thread that has been waiting the longest in the highest priority queue that contains any waiting threads. Implementations may take approaches such as these, but you can't depend on it. Implementations are free to implement the entry and wait sets as last-in-first-out (LIFO) queues, to select lower priority threads before higher priority threads, or to do anything else that may not seem to make sense. In short, implementations are free to select threads in an arbitrary manner that defies analysis and yields surprising orderings.

As a programmer, you must not rely on any particular selection algorithm or treatment of priorities, at least if you are trying to write a Java program that is platform independent. For example, because you don't know what order threads in the wait set will be chosen for resurrection by the notify command, you should use notify (as opposed to notify all) only when you are absolutely certain there will only be one thread suspended in the wait set. If there is a chance more than one thread will be suspended in the wait set at any one time, you should probably use notify all. Otherwise, on some Java virtual machine implementations a particular thread may be stuck in the wait set for a very long time. If a notify always selects the most recent arrival from the wait set and the wait set always contains multiple threads, some threads that have been waiting the longest may never be resurrected.

19 April 2012

Divide equal set of Head/Tail Coins on a table Problem

here is a table on which a number of coins are placed. You also know that there are as many coins with Head up as many coins with Tail up. Now you have to divide the coins (number of coins is even) into two equal piles such that number of coins with Heads up and Tails up in either piles be the same. The catch is you are blind folded and you cannot determine the sides (for sure) if you are blinded

Solution-

If you are totally blind and choose to create two sets of 25, 25 following four possible combinations are possible.
1. all heads are one side and all tails on other side
2. reverse for 1
3. 10H 15T, 15H, 10T
4. reverse of 3.

The following diagram pictorially represents the above four combinations. If you look properly in the diagram set2 is just a inverse of set1.
So the above four combinations can be represented as
set1 = A and set2 = INVERSE(A)


What we need is A in set2 to get equals number of H & T in both sets.
Make set2 equal to set1 = INVERSE( INVERSE(set1) = SET2) 

Extension to this Problem - Assume you have 10 coins with heads up and 42 with tails up. Can you still divide them into two sets so that they have equal number of heads.

Solution - trick is here the symmetry we were discussing above is lost causing the above inverse solution to fail. We can gain that symmtery by making both sets of different size.

Let's have set1 with 10 elements and set2 with 42 elements and the following combination's may exist.
1. set1 - 10H, 32T and set2 - 0H, 10T
2. set1 - 9H, 33T and  set2 - 1H, 9T
3. set1 - 8H,34T and set2 - 2H, 8T
....................
....................
....................
10 set1 - 0H, 42T and set2 - 10H

If you observe the above combination's carefully we have achieved symmetry in H
Since this problem is converted into the above problem we can safely apply the above solution by reversing all coins in the smaller set.