• No results found

is prepare: Each of the resources votes on whether it’s ready to commit – usually by going ahead and persisting the new data but not yet deleting the old data

Model-1 pattern

Phase 1 is prepare: Each of the resources votes on whether it’s ready to commit – usually by going ahead and persisting the new data but not yet deleting the old data

Phase 1 is prepare: Each of the resources votes on whether it’s ready to commit – usually by going ahead and persisting the new data but not yet deleting the old data.

Phase 2 is committing: If all the resources are ready, they all commit – after which old data is deleted and transaction can no longer roll back. 2-phase commit ensures that a distributed transaction can always be committed or always rolled back if one of the databases crashes. The XA specification defines how an application program uses a transaction manager to coordinate distributed transactions across multiple resource managers.

Any resource manager that adheres to XA specification can participate in a transaction coordinated by an XA-compliant transaction manager.

Q 74: What is dooming a transaction? TI

A 74: A transaction can be doomed by the following method call CO ejbContext.setRollbackOnly();

The above call will force transaction to rollback. The doomed transactions decrease scalability and if a transaction is doomed why perform compute intensive operations? So you can detect a doomed transaction as shown below:

CO

public void doComputeIntensiveOperation() throws Exception { if ( ejbContext.getRollbackOnly() ) {

return; // transaction is doomed so return (why unnecessarily perform compute intensive // operation)

} else {

performComplexOperation();

} }

Q 75: How to design transactional conversations with session beans? SF TI

A 75: A stateful session bean is a resource which has an in memory state which can be rolled back in case of any failure. It can participate in transactions by implementing SessionSynchronization. CO

The uses of SessionSynchronization are:

ƒ Enables the bean to act as a transactional resource and undo state changes on failure.

ƒ Enables you to cache database data to improve performance.

Q 76: Explain exception handling in EJB? SF EH CO FAQ

A 76: Java has two types of exceptions:

ƒ Checked exception: derived from java.lang.Exception but not java.lang.RuntimeException.

ƒ Unchecked exception: derived from java.lang.RuntimeException thrown by JVM.

public void depositAmount() throws InsufficientFundException { if(this.amount <= 0) {

throw new InsufficientFundException ("Balance is <= 0");

} try {

depositAmount();

} catch (SQLException e) { throw new EJBException(e);

} catch (Exception e) {

throw new EJBException(e);

} }

Application Exception

System Exception

System vs Application Exception

EJB has two types of exceptions:

ƒ System Exception: is an unchecked exception derived from java.lang.RuntimeException. An EJBException is an unchecked exception, which is derived from java.lang.RuntimeException.

ƒ Application Exception: is specific to an application and thrown because of violation of business rules (e.g.

InsufficierntFundException etc). An Application Exception is a checked exception that is either defined by the bean developer and does not extend java.rmi.RemoteException, or is predefined in the javax.ejb package (i.e. CreateException, RemoveException, ObjectNotFoundException etc).

A System Exception is thrown by the system and is not recoverable. For example EJB container losing connection to the database server, failed remote method objects call etc. Because the System Exceptions are unpredictable, the EJB container is the only one responsible for trapping the System Exceptions. The container

SessionSynchronization

public class MyBean implements SessionBean, SessionSynchronization{

public int oldVal ; public int val ;

public void ejbCreate(int val) throws CreateException { this.val=val;

this.oldVal=val;

}

public void afterBegin() { this.oldVal = this.val ;}

public void beforeCompletion(){};

public void afterCompletion(boolean b) { if (b == false) this.val = this.oldVal ; } ...

}

public interface javax.ejb.SessionSynchronization { public void afterBegin();

public void beforeCompletion();

public void afterCompletion(boolean b);

}

automatically wraps any RuntimeException in RemoteException, which subsequently gets thrown to the caller (i.e.

client). In addition to intercepting System Exception the container may log the errors.

An Application Exception is specific to an application and is thrown because of violation of business rules. The client should be able to determine how to handle an Application Exception. If the account balance is zero then an Application Exception like InsufficientFundException can be thrown. If an Application Exception should be treated as a System Exception then it needs to be wrapped in an EJBException, which extends java.lang.

RuntimeException so that it can be managed properly (e.g. rolling back transactions) and propagated to the client.

Q 77: How do you rollback a container managed transaction in EJB? SF TI EH FAQ

A 77: The way the exceptions are handled affects the way the transactions are managed. CO

When the container manages the transaction, it is automatically rolled back when a System Exception occurs.

This is possible because the container can intercept System Exception. However when an Application Exception occurs, the container does not intercept it and therefore leaves it to the code to roll back using ctx.setRollbackOnly().

Be aware that handling exceptions in EJB is different from handling exceptions in Java. The Exception handling best practice tips are:

ƒ If you cannot recover from System Exception let the container handle it.

ƒ If a business rule is violated then throw an application exception.

ƒ If you want to rollback a transaction on an application exception then catch the application exception and throw an EJBException or use ctx.setRollbackOnly();

Q 78: What is the difference between optimistic and pessimistic concurrency control? TI CI A 78:

Pessimistic Concurrency Optimistic Concurrency A pessimistic design assumes conflicts will occur in the

database tables and avoids them through exclusive locks etc.

An optimistic approach assumes conflicts won’t occur, and deal with them when they do occur.

EJB (also non-EJB) locks the source data until it completes its transaction.

ƒ Provides reliable access to data.

ƒ Suitable for short transactions.

ƒ Suitable for systems where concurrent access is rare.

EJB (also non-EJB) implements a strategy to detect whether a change has occurred. Locks are placed on the database only for a small portion of the time.

ƒ Suitable for long transactions.

ƒ Suitable for systems requiring frequent concurrent accesses.

The pessimistic locking imposes high locking overheads on the server and lower concurrency.

The optimistic locking is used in the context of cursors. The optimistic locking works as follows:

ƒ No locks are acquired as rows are read.

ƒ No locks are acquired while values in the current row are changed.

ƒ When changes are saved, a copy of the row in the database is read in the locked mode.

ƒ If the data was changed after it was read into the cursor, an error

Rolling back Container Managed Transactions

public void depositAmount() throws InsufficientFundExceptiion { try {

depositAmount();

}catch (InsufficientFundException e) ctx.setRollbackOnly();

throw new InsufficientFundExceptiion(e.getMessage());

} catch (SQLException e) { throw new EJBException(e);

} catch (Exception e) {

throw new EJBException(e);

} }

Application Exception is thrown so the transaction should be rolled back in the code ctx.setRollbackOnly().

EJBException is a System Exception so the container will automatically roll back the transaction.

is raised so that the transaction can be rolled back and retried.

Note: The testing for changes can be done by comparing the values, timestamp or version numbers.

Q 79: How can we determine if the data is stale (for example when using optimistic locking)? TI A 79: We can use the following strategy to determine if the data is stale:

ƒ Adding version numbers

1. Add a version number (Integer) to the underlying table.

2. Carry the version number along with any data read into memory (through value object, entity bean etc).

3. Before performing any update compare the current version number with the database version number.

4. If the version numbers are equal update the data and increment the version number.

5. If the value object or entity bean is carrying an older version number, reject the update and throw an exception.

Note: You can also do the version number check as part of the update by including the version column in the where clause of the update without doing a prior select.

ƒ Adding a timestamp to the underlying database table.

ƒ Comparing the data values.

These techniques are also quite useful when implementing data caching to improve performance. Data caches should regularly keep track of stale data to refresh the cache. These strategies are valid whether you use EJB or other persistence mechanisms like JDBC, Hibernate etc.

Q 80: What are not allowed within the EJB container? SF

A 80: In order to develop reliable and portable EJB components, the following restrictions apply to EJB code implementation:

ƒ Avoid using static non-final fields. Declaring all static fields in EJB component as final is recommended. This enables the EJB container to distribute instances across multiple JVMs.

ƒ Avoid starting a new thread (conflicts with EJB container) or using thread synchronization (allow the EJB container to distribute instances across multiple JVMs).

ƒ Avoid using AWT or Swing functionality. EJBs are server side business components.

ƒ Avoid using file access or java.io operations. EJB business components are meant to use resource managers such as JDBC to store and retrieve application data. But deployment descriptors can be used to store <env-entry>.

ƒ Avoid accepting or listening to socket connections. EJB components are not meant to provide network socket functionality. However the specification lets EJB components act as socket clients or RMI clients.

ƒ Avoid using the reflection API. This restriction enforces Java security.

ƒ Can’t use custom class loaders.

Q 81: Discuss EJB container security? SF SE

A 81: EJB components operate inside a container environment and rely heavily on the container to provide security. The four key services required for the security are:

ƒ Identification: In Java security APIs this identifier is known as a principal.

ƒ Authentication: To prove the identity one must present the credentials in the form of password, swipe card, digital certificate, finger prints etc.

ƒ Authorization (Access Control): Every secure system should limit access to particular users. The common way to enforce access control is by maintaining security roles and privileges.

ƒ Data Confidentiality: This is maintained by encryption of some sort. It is no good to protect your data by authentication if someone can read the password.

The EJB specification concerns itself exclusively with authorization (access control). An application using EJB can specify in an abstract (declarative) and portable way that is allowed to access business methods. The EJB container handles the following actions:

ƒ Find out the Identity of the caller of a business method.

ƒ Check the EJB deployment descriptor to see if the identity is a member of a security role that has been granted the right to call this business method.

ƒ Throw java.rmi.RemoteException if the access is illegal.

ƒ Make the identity and the security role information available for a fine grained programmatic security check.

public void closeAccount() {

if (ejbContext.getCallerPrincipal().getName().equals(“SMITH”)) { //…

}

if (!ejbContext.isCallerInRole(CORPORATE_ACCOUNT_MANAGER)) {

throw new SecurityException(“Not authorized to close this account”);

} }

ƒ Optionally log any illegal access.

There are two types of information the EJB developer has to provide through the deployment descriptor.

ƒ Security roles

ƒ Method permissions Example:

<security-role>

<description>

Allowed to open and close accounts </description>

<role-name>account_manager</role-name>

</security-role>

<security-role>

<description>

Allowed to read only </description>

<role-name>teller</role-name>

</security-role>

There is a many-to-many relationship between the security roles and the method permissions.

<method-permission>

<role-name>teller</role-name>

<method>

<ejb-name>AccountProcessor</ejb-name>

<method-name>findByPrimaryKey</method-name>

</method>

</method-permission>

Just as we must declare the resources accessed in our code for other EJBs that we reference in our code we should also declare the security role we access programmatically to have a fine grained control as shown below.

<security-role-ref>

<description>

Allowed to open and close accounts </description>

<role-name>account_manager</role-name>

<role-link>executive</role-link>

</security-role-ref>

There is also many-to-many relationship between the EJB specific security roles that are in the deployment descriptor and the application based target security system like LDAP etc. For example there might be more than one group users and individual users that need to be mapped to a particular EJB security role ‘account_manager’.

Q 82: What are EJB best practices? BP FAQ

A 82:

ƒ Use local interfaces that are available in EJB2.0 if you deploy both the EJB client and the EJB in the same server. Use vendor specific pass-by-reference implementation to make EJB1.1 remote EJBs operate as local.

[Extreme care should be taken not to affect the functionality by switching the application, which was written and tested in pass-by-reference mode to pass-by-value without analyzing the implications and re-testing the functionality.

ƒ Wrap entity beans with session beans to reduce network calls (refer Q84 in Enterprise section) and promote declarative transactions. Where possible use local entity beans and session beans can be either local or remote. Apply the appropriate EJB design patterns as described in Q83 – Q87 in Enterprise section.

ƒ Cache ejbHome references to avoid JNDI look-up overhead using service locator pattern.

ƒ Handle exceptions appropriately (refer Q76, Q77 in Enterprise section).

ƒ Avoid transaction overhead for non-transactional methods of session beans by declaring transactional attribute as “Supports”.

ƒ Choose plain Java object over EJB if you do not want services like RMI/IIOP, transactions, security, persistence, thread safety etc. There are alternative frameworks such as Hibernate, Spring etc.

ƒ Choose Servlet’s HttpSession object rather than stateful session bean to maintain client state if you do not require component architecture of a stateful bean.

ƒ Apply Lazy loading and Dirty marker strategies as described in Q88 in Enterprise section.

Session Bean (stateless)

Session Bean (stateful) Entity Bean

ƒ Tune the pool size to avoid overhead of creation and destruction.

ƒ Use setSessionContext(..) or ejbCreate(..) method to cache any bean specific resources.

ƒ Release any acquired resources like Database connection etc in ejbRemove() method

ƒ Tune the pool size to avoid overhead of creation and destruction.

ƒ Set proper time out to avoid resource congestion.

ƒ Remove it explicitly from client using remove() method.

ƒ Use ‘transient’ variable where possible to avoid serialization overhead.

ƒ Tune the pool size to avoid overhead of creation and destruction.

ƒ Use setEntityContext(..) method to cache any bean specific resources and unsetEntityContext() method to release acquired resources.

ƒ Use lazy-loading to avoid any unnecessary loading of dependent data. Use dirty marker to avoid unchanged data update.

ƒ Commit the data after a transaction completes to reduce any database calls in between.

ƒ Where possible perform bulk updates, use CMP rather than BMP, Use direct JDBC (Fast-lane-reader) instead of entity beans, use of read-only entity beans etc.

Q 83: What is a business delegate? Why should you use a business delegate? DP PI FAQ

A 83: Questions Q83 – Q88 are very popular EJB questions.

Problem: When presentation tier components interact directly with the business services components like EJB, the presentation components are vulnerable to changes in the implementation of business services components.

Solution: Use a Business Delegate to reduce the coupling between the presentation tier components and the business services tier components. Business Delegate hides the underlying implementation details of the business service, such as look-up and access details of the EJB architecture.

Business delegate is responsible for:

ƒ Invoking session beans in Session Facade.

ƒ Acting as a service locator and cache home stubs to improve performance.

ƒ Handling exceptions from the server side. (Unchecked exceptions get wrapped into the remote exception, checked exceptions can be thrown as an application exception or wrapped in the remote exception.

unchecked exceptions do not have to be caught but can be caught and should not be used in the method signature.)

ƒ Re-trying services for the client (For example when using optimistic locking business delegate will retry the method call when there is a concurrent access.).

Outline

Related documents