Concurrency in Java

Posted on

1. Processes and Threads

A Java program runs in its own process. Java supports within one program the usage of threads.
Java supports threads as part of the Java language. Java 1.5 also provides improved support for concurrency with the in the package java.util.concurrent.
Java also provides locks to protect certain parts of the coding to be executed by several threads at the same time. The simplest way of locking a certain method or Java class is to use the keyword “synchronized” in a method or class declaration.

2. Synchronized

The synchronized keyword in Java ensures:

  • that only a single thread can execute a block of code at the same time
  • ensures that each thread entering a synchronized block of code sees the effects of all previous modifications that were guarded by the same lock

Synchronization is necessary for mutual exclusive access of code blocks and for reliable communication between threads.

synchronized can be used directly in the definition of a method. This would ensure that only one thread can access this method. Or you can used synchronized blocks which a named block (either a string or a object). Then all code which is protected by the same lock can only be executed by one thread.
For example the following datastructure will ensure that only one thread can access the inner block of add() and next()

    
package de.vogella.pagerank.crawler;

import java.util.ArrayList;
import java.util.List;


/**
* Data structure for a web crawler. Keeps track of the visited sites and keeps
* a list of sites which needs still to be crawled.
*
* @author Lars Vogel
*
*/

public class CrawledSites {
private List<String> crawledSites = new ArrayList<String>();
private List<String> linkedSites = new ArrayList<String>();

public void add(String site) {
synchronized (this) {
if (!crawledSites.contains(site)) {
linkedSites.add(site);
}
}
}


/**
* Get next site to crawl. Can return null (if nothing to crawl)
*/

public String next() {
if (linkedSites.size() == 0) {
return null;
}
synchronized (this) {
// Need to check again if size has changed
if (linkedSites.size() > 0) {
String s = linkedSites.get(0);
linkedSites.remove(0);
crawledSites.add(s);
return s;
}
return null;
}
}

}

3. Volatile

If a variable is declared as volatile then is guaranteed that any thread which reads the field will see the most recently written value. The keyword volatile will not perform any mutual exclusive lock on the variable.
As of Java 5 write access to a volatile variable will also update non-volatile variables which were modified by the same thread. This can also be used to update values within a reference variable, e.g. for a volatile variable person. In this case you must use a temporary variable person and use the setter to initialize the variable and then assign the temporary variable to the final variable. This will then make the address changes of this variable and the values visible to other threads.

Concurrency

Posted on

1. Concurrency

1.1. Overview

Concurrency is the ability to run several parts of a program or several programs in parallel. Concurrency can highly improve the throughput of a program if certain tasks can be performed asynchronously or in parallel.
Almost every computer nowadays has several CPU’s or several cores within one CPU. The ability to leverage these multi-cores can be the key for a successful high-volume application.

1.2. Process vs. threads

The distinction between processes and threads is important.

  • Process: A process runs independently and isolated of other processes. It cannot directly access shared data in other processes. The resources of the process are allocated to it via the operating system, e.g. memory and CPU time.
  • Threads: threads are so called lightweight processes which have their own call stack but an access shared data. Every thread has its own memory cache. If a thread reads shared data it stores this data in its own memory cache. A thread can re-read the shared data, when this happens in Java will be explained in Java memory model part of this article.

Within a Java application you work with several threads to achieve parallel processing or asynchronous behavior.

1.3. Amdahl’s Law

Concurrency promises to perform certain task faster as these tasks can be divided into subtasks and these subtasks can be executed in parallel. Of course the runtime is limited by parts of the task which can be performed in parallel. The theoretical possible performance gain can be calculated by Amdahl’s Law. If F is the percentage of the program which can not run in parallel and N is the number of processes then the maximum performance gain is 1/ (F+ ((1-F)/n)).

1.4. Concurrency issues

Threads have there own call stack but can also access shared data. Therefore you have two basic problems, visibility and access problems.
A visibility problem occurs if one thread reads shared data which is later changed by other thread and if thread A does not see this change.
A access problem occurs if several thread trying to access and change the same shared data at the same time.
Visibility and access problem can lead to

OJMCEA Notes

Posted on

OOP:
Inheritance: inherit properties and method from object
Abstraction: Essential character distinguish from other object
Encapsulation: Seperation (hiding) external aspect
Polymorphism: assign different behaviour to something that was declared in a parent class

2 tier architecture model:
Cons:
1. validation intensive
2. each client need to make connection directly
3. not very maintainable
4. only horizontal scalability ?

webservice features:
Static and dynamic client call
Synchronous and Asynchronous WS call

SOAP Authentication:
WS Header
SOAP Message:
1. Require Envelope
2. Optional Header
3. Require Body
4.  Optional Fauilt

JAX-WS: client doesn’t need WSDL and XML document

Strategy design pattern:
subclassing alternative
eleminate conditional statement
extend model without change code

Template method:
Skeleton of an algorithm

Proxy:
placeholder for other object to control/access it

Decorator:
pre and post processing .

Service Activator:
Invocation of business service / EJB without  waiting for the result
Integration of publish/subscribe and point to point messaging
Perform business task that locigally composed of several business task

MTOM: Sending binary from/to webservices

Signed jar: 
Doesn’t mean that the sender is authentic,

Web.xml deployment descriptor:
1. protected url
2. authentication mechanism

JSF Phase:
Request:
Restore View
Apply Request
Validation
 Response:
Update Model
Invoke
Render


Servlet destroy for:
Keep track how many thread running
Clean shutdown by having destroy method, notify long running thread & wait to complete
Long running method poll periodically, check shutdown, or if stop working, clean and return

 N-TIERS:
Client Tier
Web Tier
EJB Tier / Business Tier
EIS Integration Tier
EIS TIer

JMS:
Note: JMS doesn’t define functionality that addresses load balancing, fault tolerance, security, and administration. Such mechanisms must be provided by JMS providers.

 MDB:
MDB not accessed via interface
Instance variable of MDB can keep state accross handling of client message

BASIC OOP:
Encapsulation
Inheritance
Polymorphism

Delegation
Delegation is the simple yet powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation where one object defers a task to another object, known as the delegate

JSF: How to pass parameter to Managed Bean

Posted on

Use <f:param> instead. It adds a request parameter.
<h:commandLink action=”#{bean.insert}” value=”insert”>
<f:param name=”id” value=”#{item.id}” />
</h:commandLink>

If your bean is request scoped, let JSF set it by @ManagedProperty
@ManagedProperty(value=”#{param.id}”)
private Long id; // +setter

Or if your bean has a broader scope or if you want more fine grained validation/conversion, use <f:viewParam> on the target view, see also f:viewParam vs @ManagedProperty:
<f:viewParam name=”id” value=”#{bean.id}” required=”true” />

Either way, this has the advantage that the datamodel doesn’t necessarily need to be preserved for the form submit (for the case that your bean is request scoped).

Use <f:setPropertyActionListener> instead. The advantage is that this removes the need for accessing the request parameter map when the bean has a broader scope than the request scope.
<h:commandLink action=”#{bean.insert}” value=”insert”>
<f:setPropertyActionListener target=”#{bean.id}” value=”#{item.id}” />
</h:commandLink>

In combination with
private Long id; // +setter

It’ll be just available by property id in action method. This only requires that the datamodel is preserved for the form submit request. Best is to put the bean in the view scope by @ViewScoped.

If your servletcontainer supports Servlet 3.0 / EL 2.2, then just pass it as method argument. This also requires that the datamodel is preserved for the form submit request. Best is to put the bean in the view scope by @ViewScoped.
<h:commandLink action=”#{bean.insert(item.id)}” value=”insert” />

In combination with:
public void insert(Long id) {
// …
}

You can even pass the entire item object:
<h:commandLink action=”#{bean.insert(item)}” value=”insert” />

with:
public void insert(Item item) {
// …
}

On Servlet 2.5 containers, this is also possible if you supply an EL implementation which supports this, like as JBoss EL. For configuration detail, see this answer.

Bind the datatable value to DataModel<E> instead which in turn wraps the items.
<h:dataTable value=”#{bean.model}” var=”item”>

with
private transient DataModel<Item> model;

public DataModel<Item> getModel() {
if (model == null) {
model = new ListDataModel<Item>(items);
}
return model;
}

(making it transient and lazily instantiating it in the getter is mandatory when you’re using this on a view or session scoped bean since DataModel doesn’t implement Serializable)

Then you’ll be able to access the current row by DataModel#getRowData() without passing anything around (JSF determines the row based on the request parameter name of the clicked command link/button).
public void insert() {
Item item = model.getRowData();
Long id = item.getId();
// …
}

This also requires that the datamodel is preserved for the form submit request. Best is to put the bean in the view scope by @ViewScoped.

You can use Application#evaluateExpressionGet() to programmatically evaluate the current #{item}.
public void insert() {
FacesContext context = FacesContext.getCurrentInstance();
Item item = context.getApplication().evaluateExpressionGet(context, “#{item}”, Item.class);
Long id = item.getId();
// …
}

Which way to choose depends on the functional requirements and whether the one or the other offers more advantages for other purposes. I personally would go ahead with #3 or, when you’d like to support servlet 2.5 containers as well, with #2.

source
http://stackoverflow.com/questions/4994458/how-can-i-pass-a-parameter-to-a-commandlink-inside-a-datatable

Hibernate, postgreSQL, jboss-7

Posted on Updated on

When we start a project,  The most-time consuming task is to initialize the environment and setup a new connection (ORM, Database, EJB etc). Today, I will explain how to setup database connection using Hibernate, Java2ee, JBOSS 7, Eclipse Indigo.

Step by step:
1. Install Eclipse 3.7.2 indigo ide for java-ee developer(http://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/indigosr2)
2. Install Jboss Tools 3.3 for eclipse indigo (https://www.jboss.org/tools/download/installation/update_3_3.html)
3. Create a new Dynamic Web project under Jboss Central

Dynamic Web Project

4. Click Modify button to open Project Facet, and the following screen will pop up:

Project Facets

5. Tick JPA to enable database connection via hibernate.Then  Click Ok to save and close the windows.
6. Unfortunately, the configuration screen to build persistence.xml doesn’t function very well, I need to manually modify it.
 Following is the persistence.xml example to connect to postgresql:

<?xml version=”1.0″ encoding=”UTF-8″?>
<persistence version=”2.0″ xmlns=”http://java.sun.com/xml/ns/persistence&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd”&gt;
   
    <persistence-unit name=”nbs_web” transaction-type=”RESOURCE_LOCAL”
        >
        <class>com.etrade.managedbean.UserBean</class>
        <properties>
            <property name=”javax.persistence.jdbc.url” value=”jdbc:postgresql://localhost:5432/test”/>
            <property name=”javax.persistence.jdbc.user” value=”test”/>
            <property name=”javax.persistence.jdbc.password” value=”test”/>
            <property name=”javax.persistence.jdbc.driver” value=”org.postgresql.Driver”/>
          
            <property name=”hibernate.dialect” value=”org.hibernate.dialect.PostgreSQLDialect”/>
            <property name=”hibernate.connection.driver_class” value=”org.postgresql.Driver”/>
            <property name=”hibernate.connection.url” value=”jdbc:postgresql://localhost:5432/test”/>
            <property name=”hibernate.default_schema” value=”public”/>
            <property name=”hibernate.connection.username” value=”test”/>
            <property name=”hibernate.connection.password” value=”test”/>
          
          
          
            <property name=”hibernate.show_sql” value=”true”/>
            <property name=”hibernate.format_sql” value=”true”/>
          
        </properties>
                   

    </persistence-unit>
</persistence>

8. Following is the directory structure , where you should put your  persistence.xml and postgresql driver:

9. Database setup is ready. Now we will need to do the java code.

GlassFish V3 admin console taking too much time to load

Posted on

GlassFish V3 admin console taking too much time to load.

If you have installed Glassfish V3 and trying to load admin console, but after signing in, is it taking too much time to get to the main page ? Do you have server.log entry like this:

admin console: initSessionAttributes()
Cannot refresh Catalog : Connection timed out

then its time to tweak some files. Here its how:

1. Update the %GLASSFISH_HOME/glassfish/domains/domain1/domain.xml

  1. <java-config>
  2. <jvm-options>-Dcom.sun.enterprise.tools.admingui.NO_NETWORK=true<!–jvm-options>
  3. <!–java-config>

This will block up the News item, the registration item, etc

2. Remove update tool jar
(Backup and remove this JAR)

%GLASSFISH_HOME/glassfish/modules/console-updatecenter-plugin.jar

Delete this dir:

%GLASSFISH_HOME/glassfish/domains/domain1/osgi-cache

%GLASSFISH_HOME/glassfish/domains/domain1/generated

Now start the server (bin/asadmin start-domain) and you will see the admin console won’t be hang up and take you directly to main page.

copy from:
http://techmythoughts.blogspot.com/2010/08/glassfish-v3-admin-console-taking-too.html

Adapter Pattern

Posted on

Definition
In computer programming, the adapter pattern (often referred to as the wrapper pattern or simply a wrapper) is a design pattern that translates one interface for a class into a compatible interface. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms. For instance, if multiple boolean values are stored as a single integer (i.e. flags) but your client requires a ‘true’/’false’, the adapter would be responsible for extracting the appropriate values from the integer value. Another example is transforming the format of dates (e.g. YYYYMMDD to MM/DD/YYYY or DD/MM/YYYY).

There are two types of adapter patterns:

Object Adapter pattern

In this type of adapter pattern, the adapter contains an instance of the class it wraps. In this situation, the adapter makes calls to the instance of the wrapped object.

The object adapter pattern expressed in UML. The adapter hides the adaptee’s interface from the client.

The object adapter pattern expressed in LePUS3.

Class Adapter pattern

This type of adapter uses multiple polymorphic interfaces to achieve its goal. The adapter is created by implementing or inheriting both the interface that is expected and the interface that is pre-existing. It is typical for the expected interface to be created as a pure interface class, especially in languages such as Java that do not support multiple inheritance.

The class adapter pattern expressed in UML.

The class adapter pattern expressed in LePUS3

The adapter pattern is useful in situations where an already existing class provides some or all of the services you need but does not use the interface you need. A good real life example is an adapter that converts the interface of a Document Object Model of an XML document into a tree structure that can be displayed. A link to a tutorial that uses the adapter design pattern is listed in the links below.

A further form of runtime Adapter pattern

There is a further form of runtime Adapter pattern as follows:

It is desired for classA to supply classB with some data, let us suppose some String data. A compile time solution is:


classB.setStringData(classA.getStringData()); 

However, suppose that the format of the string data must be varied. A compile time solution is to use inheritance:

Format1ClassA extends ClassA {    public String getStringData() {       return format(toString());    } }



and perhaps create the correctly “formatting” object at runtime by means of the Factory pattern.

A solution using “adapters” proceeds as follows:

(i) define an intermediary “Provider” interface, and write an implementation of that Provider interface which wraps the source of the data, ClassA in this example, and outputs the data formatted as appropriate:

public interface StringProvider {     public String getStringData(); }   public class ClassAFormat1 implements StringProvider {     ClassA classA;       public ClassAFormat1(ClassA classA) {         this.classA = classA;     }       public String getStringData() {         return format(classA.toString());     } }

(ii) Write an Adapter class which returns the specific implementation of the Provider:

public class ClassAFormat1Adapter extends Adapter {    public Object adapt(Object o) {       return new ClassAFormat1((ClassA) o);    }      public boolean isAdapterFor(Class c) {       return c.equals(StringProvider.class);    } }

(iii) Register the Adapter with a global registry, so that the Adapter can be looked up at runtime:

AdapterFactory.getInstance().registerAdapter(ClassA.class, ClassAFormat1Adapter.class, "format1");

(iv) In your code, when you wish to transfer data from ClassA to ClassB, write:

Adapter adapter = AdapterFactory.getInstance().getAdapterFromTo(ClassA.class, StringProvider.class, "format1"); StringProvider provider = (StringProvider) adapter.adapt(classA); String string = provider.getStringData(); classB.setStringData(string);

or more concisely:

classB.setStringData(((StringProvider) AdapterFactory.getInstance().getAdapterFromTo(ClassA.class, StringProvider.class, "format1").adapt(classA)).getStringData());

(v) The advantage can be seen in that, if it is desired to transfer the data in a second format, then look up the different adapter/provider:

Adapter adapter = AdapterFactory.getInstance().getAdapterFromTo(ClassA.class, StringProvider.class, "format2");

(vi) And if it is desired to output the data from ClassA as, say, image data in Class C:

Adapter adapter = AdapterFactory.getInstance().getAdapterFromTo(ClassA.class, ImageProvider.class, "format1"); ImageProvider provider = (ImageProvider) adapter.adapt(classA); classC.setImage(provider.getImage());

(vii) In this way, the use of adapters and providers allows multiple “views” by ClassB and ClassC into ClassA without having to alter the class hierarchy. In general, it permits a mechanism for arbitrary data flows between objects which can be retrofitted to an existing object hierarchy.

Implementation of Adapter pattern

When implementing the adapter pattern, for clarity use the class name [AdapteeClassName]To[Interface]Adapter, for example DAOToProviderAdapter. It should have a constructor method with adaptee class variable as parameter. This parameter will be passed to the instance member of [AdapteeClassName]To[Interface]Adapter.


Class SampleAdapter implements ClientClass {     private AdapteeClass mInstance;     public SampleAdapter(AdapteeClass instance)     {          mInstance=instance;     }     @Override     public void ClientClassMethod()     {        // call AdapteeClass's method to implement ClientClassMethod     }   }