Monday, March 05, 2007
ThreadLocal – A Wrapper Class for Thread Safe
Basically the template thread-safe is fulfilled by using a wrapper class "ThreadLocal". The following code provides a simple example that shows how the ThreadLocal class work.
private static ThreadLocal pi = new ThreadLocal();
public Double pi() {
if (pi.get() == null) {
pi.set(new Double(22 / 7));
}
return (Double)pi.get();
}
ThreadLocal class wraps any object and binds it to the current thread thus making objects local to the thread. When a thread executes the pi() method for the first time there will be no object bound to the thread by ThreadLocal instance pi so the get() method will return null.The set() method will bind an object to the thread that is not shared by other threads. If the method pi() is called often per thread this approach may still offer a considerable performance gain while guaranteeing thread-safety.
Thursday, February 22, 2007
Is RMI Thread Safe?
According to the specification defined with Java 1.4.2, RMI section 3.2,
A method dispatched by the RMI runtime to a remote object implementation may or may not execute in a separate thread. The RMI runtime makes no guarantees with respect to mapping remote object invocations to threads. Since remote method invocation on the same remote object may execute concurrently, a remote object implementation needs to make sure its implementation is thread-safe.No matter how confusing this specification is, it at least tells us two things,
- RMI does not take care of the thread safety, it leaves the thread safety as it is.
- RMI does not give you one server thread for one client thread, actually, it guarantees nothing on the thread scheduling.
As long as both the client objects and the server objects are thread-safe, the application is thread-safe.
Wednesday, February 21, 2007
Please! Don't Thread Safe Everything!
- Unnecessary synchronized method invocations (and synchronized blocks) can cause unnecessary blocking and unblocking of threads, which can hurt performance.
- Immutable objects tend to be instantiated more often, leading to greater numbers of often short-lived objects that can increase the work of the garbage collector.
- Synchronization gives rise to the possibility of deadlock, a severe performance problem in which your program appears to hang.
Way to Thread Safety - Wrapper
This approach makes the most sense when you want to give clients a choice between a version of a class that is thread-safe and one that isn't. It also makes sense when you're a client of someone else's class that isn't thread-safe, but you need to use the class in a multithreaded environment. Once you define your own thread-safe wrapper for the class, you can safely use the class in a multithreaded environment by going through your wrapper.
A good example of this approach from the Java API comes from the 1.2 collections library. The 1.2 collections library defines a hierarchy that includes classes that represent many kinds of collections -- none of which are thread-safe. But class Collection includes several class methods that will enclose a regular collection object in a thread-safe wrapper, so you can safely use the object in a multithreaded context. This design gives users of the collections library a choice of using a collections object that is thread-safe and one that isn't.
Note that a common attribute of wrapper classes like those you would use to add thread safety to the enclosed object is that the wrapper accepts the same messages as the enclosed object. In other words, often a wrapper class will descend from a common superclass or superinterface with the enclosed class. (For those of you familiar with the Design Patterns book by Gamma, et. al., this is the "decorator" pattern.) This decorator design approach to wrappers, which is exhibited by the thread-safe wrappers of the 1.2 collections library, allows the thread safety to be dynamically added or removed from an object.
Way to Thread Safety - Immutable
In this approach to making an object thread-safe, you don't mark critical sections as synchronized. Instead, you separate out the critical sections that read instance variables from those that write to instance variables. The critical sections that read are left as-is. The critical sections that write must be changed so that, instead of altering the current object's instance variables, they create a new object that embodies the new state and returns a reference to that object.
String and the primitive type wrappers such as Integer, Long, Float, Boolean, Character, and so on.It also lets you pass references to them to methods without worrying that the method will change the object's state. In addition, if the overhead of immutability (excessive creation of short-lived objects) may at times be too inefficient, you can also define a mutable companion class that can be used when the immutable version isn't appropriate. An example of this design approach in the Java API is the StringBuffer class, which serves as a mutable companion to the immutable String class. Note that the StringBuffer class is also thread-safe, but it uses the "normal" approach: its instance variables are private and its critical sections are synchronized.
Way to Thread Safety - Synchronization
An object's critical sections are those methods or blocks of code within methods that must be executed by only one thread at a time. Put another way, a critical section is a method or block of code that must be executed atomically, as a single, indivisible operation. By using Java's
synchronized keyword, you can guarantee that only one thread at a time will ever execute the object's critical sections.This approach takes two steps, to make all relevant fields private, and to identify and synchronize all the critical sections.
Any field that you need to coordinate multithreaded access to must be private, otherwise it may be possible for other classes and objects to ignore your critical sections and access the fields directly. Not every field must be private - only those that will be involved in any temporarily invalid states created by the object's or class's critical sections. For example, constants (static final variables) can't be corrupted by multiple threads, so they needn't be private.
A critical section is a bit of code that must be executed atomically, that is, as a single, indivisible operation.
Note that reads and writes of primitive types and object references are atomic by definition, except for longs and doubles. This means that if you have an int, for example, that is independent of any other fields in an object, you needn't synchronize code that accesses that field. If two threads were to attempt to write two different values to the int concurrently, the resulting value would be one or the other. The int would never end up with a corrupted value made up of some bits written by one thread and other bits written by the other thread.
The same is not necessarily true, however, for longs and doubles. If two different threads were to attempt to write two different values to a long concurrently, you might just end up with a corrupted value consisting of some bits written by one thread and other bits written by the other thread. Multithreaded access to longs and doubles, therefore, should always be synchronized.
For example, a Price class has two instances variables, double priceValue and Date effectiveDate. And the class has a updatePrice method,
public void updatePrice(doubel priceValue, effectiveDate) {this.priceValue = priceValue;
this.effectiveDate = effectiveDate;
}
The way to make Price thread safe is to make the priceValue and the effectiveDate private first,
then synchronize the updatePrice method.
public synchronized void updatePrice(double priceValue, effectiveDate) {
...
}
or
public void ... {
synchronized (this) {
this.priceValue = priceValue;
this.effectiveDate = effectiveDate;
}
}
Thread Safety - How to Tell
Write/write conflicts
Imagine two threads are trying to write to the same object's instance variables concurrently. If the thread scheduler interleaves these two threads in just the right way, the two threads will inadvertently interfere with each other, yielding a write/write conflict. In the process, the two threads will corrupt the object's state.
Read/write conflicts
This kind of conflict arises when an object's state is read and used while in a temporarily invalid state due to the unfinished work of another thread.
This is like the ACID characteristics of transactions. As long as it takes two or more steps to move an instance from one state to another state, the class is very unlikely thread safe.
Tuesday, February 20, 2007
Thread Safety - Where to Worry About
Given the architecture of the JVM, you need only be concerned with instance and class variables when you worry about thread safety. Because all threads share the same heap, and the heap is where all instance variables are stored, multiple threads can attempt to use the same object's instance variables concurrently. Likewise, because all threads share the same method area, and the method area is where all class variables are stored, multiple threads can attempt to use the same class variables concurrently. When you do choose to make a class thread-safe, your goal is to guarantee the integrity -- in a multithreaded environment -- of instance and class variables declared in that class.
You needn't worry about multithreaded access to local variables, method parameters, and return values, because these variables reside on the Java stack. In the JVM, each thread is awarded its own Java stack. No thread can see or use any local variables, return values, or parameters belonging to another thread.
Five Categories of Thread Safety
- Immutable objects are guaranteed to be thread-safe, and never require additional synchronization. Because an immutable object's externally visible state never changes, as long as it is constructed correctly, it can never be observed to be in an inconsistent state. Most of the basic value classes in the Java class libraries, such as
Integer,String, andBigInteger, are immutable. - Thread-safe classes are safe not only for single call, but also for multiple calls combined. They will need no additional synchronzation from their callers. This thread-safety guarantee is a strong one -- many classes, like
HashtableorVector, will fail to meet this stringent definition. - Conditionally thread-safe classes are those for which each individual operation may be thread-safe, but certain sequences of operations may require external synchronization. The most common example of conditional thread safety is traversing an iterator returned from
HashtableorVector-- the fail-fast iterators returned by these classes assume that the underlying collection will not be mutated while the iterator traversal is in progress. To ensure that other threads will not mutate the collection during traversal, the iterating thread should be sure that it has exclusive access to the collection for the entirety of the traversal. Typically, exclusive access is ensured by synchronizing on a lock -- and the class's documentation should specify which lock that is (typically the object's intrinsic monitor). - Thread-compatible classes are not thread-safe, but can be used safely in concurrent environments by using synchronization appropriately. This might mean surrounding every method call with a
synchronizedblock or creating a wrapper object where every method is synchronized (likeCollections.synchronizedList()). Or it might mean surrounding certain sequences of operations with asynchronizedblock. To maximize the usefulness of thread-compatible classes, they should not require that callers synchronize on a specific lock, just that the same lock is used in all invocations. Doing so will enable thread-compatible objects held as instance variables in other thread-safe objects to piggyback on the synchronization of the owning object. Many common classes are thread-compatible, such as the collection classesArrayListandHashMap,java.text.SimpleDateFormat, or the JDBC classesConnectionandResultSet. - Thread-hostile classes are those that cannot be rendered safe to use concurrently, regardless of what external synchronization is invoked. Thread hostility is rare, and typically arises when a class modifies static data that can affect the behavior of other classes that may execute in other threads. An example of a thread-hostile class would be one that calls
System.setOut().
Monday, February 19, 2007
Generic Five Steps to Create JAX-RPC Web Service
For the second stage, you typically run some kind of mapping tool to generate the WSDL description for the web service which maps the interface.
The third step is to run a mapping tool on the WSDL file to create the stub and tie classes which are required to allow remote client access.
The next step is to compile all the generated files and package them into an archive file, typically a WAR (Web Application Archive) file.
Finally, you deploy the web service onto a web server with a built-in SOAP engine.
Decompile .class in Eclipse
OK yes, you can do this.
- download JAD at http://www.kpdus.com/jad.html and then install it on your workstation.
- download JAD Eclipse plugin at http://sourceforge.net/projects/jadclipse/ and then install it with your Eclipse.
- restart your Eclipse and click Window->Preferences->Java->JadClipse and finish the configuration.
Wednesday, January 03, 2007
Property Editor Not Visible in Weblogic Workshop 8.1
Search for the .workshop.pref and .workshop.zpref. Move them to another folder, e.g. the desktop.
Restart Workshop, the Property Editor will be visible. You will also notice that these two files will be recreated.
Monday, December 11, 2006
netui drop-down list
You need to set attributes of the Form Bean if the value of the drop-down list is associated with the Form Bean. Or the default value such as 0 for int will be inserted into the list.
Thursday, December 07, 2006
JAXP Introduction
It allows you to plug in different DOM and SAX parsers, and XSLT (Extensible Stylesheet Language Transformation) transformers, as you require without needing to change your code. This is known as a pluggablility layer. The processor can be set by changing the appropriate environment variable. Attention, it doesn't mean you can swap between DOM and SAX.
JAXP also comes with its own default parsers that implement SAX and DOM functionality.
Simple API for XML (SAX) is an API for event-based parsing of XML documents. This means a SAX parser reads the XML document from beginning to end using a data stream. Any time it encounters a new element, it throws an event to notify the application running it. The application can then handle these events as required.
SAX comes with a number of methods that you can use to recognize an event. You then respond to these events by either implementing a specific interface or extending the default handler and overriding the appropriate method. SAX does not allow you to modify the XML document, it can only read it.
The Document Object Model (DOM) API is a World Wide Web Consortium (W3C) specification for parsing XML. It builds a representation of an XML document in memory in a tree structure. You can navigate this tree to search for elements, which correspond to branches. You can also insert new elements into the tree and remove elements.
When deciding which type of parser to use you should bear in mind your needs. The SAX API is fast, as it examines the XML serially. The DOM API is much more memory-intensive and CPU-intensive, as it must load the whole document. However, the DOM API allows you to modify the XML structure and has greater flexibility. You should choose the API that provides the best tradeoff between your requirements and the limitations of your system.
JAXP also supports XSLT, a language used for transforming XML documents into other documents using stylesheets. For example, using XSLT, you could transform an XML document into HTML, or you could make an XML document based on one schema conform to another schema.
Tuesday, December 05, 2006
Servlet and Web Service
- parsing the SOAP envelope
- validating the message format and the XML
- converting any necessary data to Java specific data types
- extracting all the necessary method call information from the SOAP message and calling the other components for the J2EE system correctly using this information.
Java API for XML
- JAXP is the Java API for XML processing. It allows you to process and transform XML documents using DOM(Document Object Mode), SAX(Simple API for XML), and XSLT(eXtensible Stylesheet Language Transformations). It also allows you to switch between implementations of these standards - for example, from one DOM parser to another - without needing to alter the code.
- JAXB stands for the Java Architecture for XML Binding. It provides a mechanism for mapping between XML elements and Java objects. It compiles your XML schema into Java classes. These generated classes can then handle and parse any XML data as well as checking that al the XML you use is compliant with your requirements. It is an alternative way of processing XML to that provided by the JAXP API.
- SAAJ is the SOAP with Attachments API for Java. It is the basic package for SOAP messaging and allows you to create and populate a SOAP message.
- JAX-RPC is the Java API for XML-based remote procedure calls. It enables you to build SOAP-based applications with RPC functionality in which the method calls are encapsulated in the SOAP messages.
- JAXM is the Java API for XML Messaging. It enables applications to send and receive document-based XML messages. It implements the SOAP 1.1 standard to allow you to focus on sending the SOAP messages rather than creating low-level XML routines. It also facilitates asynchronous communications between web services.
- JAXR is the Java API for XML Registries. It allows you to access different XML registries. Among the registries it allows you to access are those based on the UDDI and ebXML(Electronic Business XML) specifications.
Monday, December 04, 2006
Entity Bean and Exception
A predefined exception is alreay part of a Java package and is provided to deal with common problems that arise within EJBs, for example, the CreateException.
Friday, December 01, 2006
Life Cycle of Entity Bean
When the bean is in the Does Not Exist state, no instance of the bean has been instantiated yet.
In the pooled state, several instances of the bean's implementation class are instantiated but are not associated with any EJBObject. All the bean instances in the pool are the same and are not associated with any database data or actively dealing with any client request.
Once the bean is instantiated, a reference to its javax.ejb.EntityContext is passed to it by the container using the bean's setEntityContext method.
Once the EntityContext is associated witht the bean, it can be placed in the pool. When the EJB server starts up, it will maintain a separate instance pool for each type of bean deployed by placing a number of bean instances in this pooled state.
Beans in the pooled state can be used to service ejbFindxxx requests, as these methods don't rely on the bean instance's state.
When a client requests a bean, the container creates an EJBObject for that bean, and it assigns a bean instance from any of the instances in the relevant instance pool to the EJBObject, using the appropriate data to initialize the bean.
This is done using the ejbCreate or ejbActivate method.
When a bean instance is assigned to an EJBObject, it moves to the ready state. In this state, the bean instance is associated with data and actively deals with client requests.
The bean instance can also use its EntityContext to receive information about the client that is using the instance and to receive callback methods from the container.
Initialized entity bean instances correspond to actual entries in a database, so, in the ready state, a bean instance can access a row of data from a database.
The ejbLoad and ejbStore callback methods, which the container uses to synchronize the bean's state with the database, can be called only when the bean is in the ready state.
Entity beans can move from the pooled state to the ready state in these circumstances,
- when a new entity bean instance is created using the ejbCreate method
- when the container activates a bean in response to a query using the ejbActivate method
- when the container uses ejbActivate to activate a bean that has previously been passivated.
To deal with this, the EJB container can passivate the bean - that is, return the bean to the pooled state - when it's not in use. It does this by invoking the ejbPassivate method.
And if a bean instance is required again, any one of the equivalent bean instances in the pooled state can be reassigned to the EJB object.
After the client request is completed with a bean instance, the bean instance can be removed and returned to the pooled state.
When the client signals that it wants to remove a bean, the container calls the ejbRemove method on the bean instance.
The life cycle of an entity bean ends when the bean instance is removed from the pool by the container to be destroyed.
If a bean is to be released, the unsetEntityContext method is called by the container to warn the bean instance that is about to be destroyed. This allows the bean instance to discharge any data it maintains before being destroyed.
Entity Bean and Transaction
In this case, the container manages the bean's transactions and is informed by the bean provider how the bean participates in a transaction. When a bean is transactional. it can be shared between multiple clients.
Session beans can be uniquely identified by an ID generated by the container. But such IDs are not enough for entity beans, since they are associated with data in a database.
Therefore, entity beans make use of the primary key class that uniquely identify the data in the database that the entity bean is associated with. So the primary key uniquely identifies both the entity bean and the underlying data in the database.
Wednesday, November 22, 2006
EJB Object and EJB Home
During deployment, EJB object and EJB home are automatically created (by J2EE servers) for entity and session beans.
The EJB object, which acts as a request interceptor, implements the bean's component interface and provides a reference to an invoked bean. The EJB home, which is an EJB object factory, implements the bean's home interface and is responsible for creating, removing, and locating enterprise beans.
As message-driven beans respond only to asynchronous messages, they do not have component or home interfaces and so have no corresponding EJB object or EJB home.