• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/87

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

87 Cards in this Set

  • Front
  • Back

¿COMO SE CLASIFICAN LOS SESSION BEANS? (3 TIPOS)

STATELESS, STATEFUL Y SINGLETON

CUANDO EL NUMERO DE REQUESTS CONCURRENTES PARA UN STATELESS SESSION BEAN EXCEDE EL TAMAÑO DEL POOL, ¿QUE SUCEDE CON LOS REQUESTS QUE NO PUEDEN SER ATENDIDOS?

The basic idea behind instance pooling is to reuse a predefined number of bean instances to service incoming requests. Whenever a request arrives for a bean, the container allocates a bean. When the stateless session bean’s method returns, the bean is placed back into the pool. Thus, a bean is either servicing a request or waiting for a request in the pool. Pools have an upper bound. If the number of concurrent requests for a stateless session bean exceeds the size of the pool, the requests that can’t be handled are placed in a queue.

¿QUE ES EL SEDA MODEL? DESCRIBIR

The pool provides several important benefits. Having a minimum set of beans in
the pool ensures that there are objects ready to service a request when one arrives.
This reduces the overall time to service a request by creating beans beforehand.
Reusing bean instances when possible instead of frivolously discarding them also
means less total object creation and destruction for the application, which saves time
for the JVM garbage collector. Lastly, specifying an upper limit of the pool acts as an
effective bandwidth-throttling mechanism. Without an effective bandwidth-throttling
mechanism, a machine could be easily overwhelmed with a sudden burst of concurrent requests. Bandwidth throttling ensures that the server performs gracefully even under heavy load. Dynamic pools, bandwidth throttling, and request queuing are
essential elements of the proven staged event-driven architecture (SEDA) model
central to highly concurrent, well-conditioned, dependable, scalable, modern internet services.

¿POR QUE EL TAMAÑO MINIMO DEL POOL EN LA MAYORIA DE APP SERVERS ACTUALES ES CERO?

¿EN QUE CASOS SE RECOMENDA ESPECIFICAR UN TAMAÑO MINIMO DE POOL Y POR QUE?

You should definitely specify a sensible minimum pool size if you’re not using
generational garbage collection (for example, to reduce garbage collection overhead or
minimize garbage collection pauses) or if your JVM doesn’t support generational garbage collection. In such cases, caching and reusing objects will significantly boost
garbage collection performance. You should also utilize minimum pool sizes for objects
that are particularly heavyweight, slow to construct, or use resources that aren’t pooled
like raw TCP-based connections.

¿CUAL ES EL CRITERIO RECOMENDADO PARA EL TAMAÑO MAXIMO DEL POOL?

It’s almost always a good idea to specify a maximum pool size to safeguard against
resource starvation caused by sudden bursts of concurrent requests. The typical default
value of maximum pool sizes is between 10 and 30. As a general rule of thumb, you
should set a maximum pool size matching the highest normally expected number of concurrent users you have for a given service. Too low a number will make the application
appear unresponsive with long wait queues, whereas too high a number will risk resource
starvation under heavy load.

¿PARA QUE SIRVE LA ANOTACION @RESOURCE? DE EJEMPLOS.

The @Resource annotation is used to perform injection
of a JDBC data source . Example:

@Stateless(name = "BidService")
public class DefaultBidService implements BidService {
private Connection connection;
@Resource(name = "jdbc/ActionBazaarDB")
private DataSource dataSource;
...
}

¿EN DONDE SON REGISTRADOS LOS EJB DE UNA APLICACION PARA SU REFERENCIA?

In JNDI.

DESCRIBA LA RELACION ENTRE EL CONTENEDOR, LOS EJB Y JNDI Y EL PROCESO EN QUE INTERACTUAN.

The name parameter (e.g. in @Stateless) specifies the name of the bean. Containers use this parameter to bind the EJB to the global JNDI tree. JNDI is essentially the application server’s
managed resource registry. All EJBs automatically get bound to JNDI as soon as the
container discovers them.

¿QUE PARAMETRO UTILIZA EL CONTENEDOR PARA REGISTRAR UN STATELESS BEAN EN EL JNDI?

The 'name' parameter in the annotation (e.g. @Stateless)

¿CUALES SON LAS FORMAS EN QUE UN CLIENTE PUEDE ACCEDER A UN SESSION BEAN Y BAJO QUE CONDICIONES?

Clients of session beans have three different ways of invoking these beans. The first is
through the local interface within the same JVM. The second is through a remote
interface using RMI. The third way that stateless session beans can be invoked is via
SOAP or REST web services. The same session bean may be accessed by any number of
these methods.

These three methods of accessing a stateless session bean are denoted using annotations. Each of these three annotations must be placed on an interface that the bean
then implements.

¿CUAL ES EL TIPO POR DEFECTO DE UNA INTERFAZ DE EJB EN CASO DE NO ESPECIFICAR?

Local interfaces are the easiest to define and use. They’re also by far the most common type of EJB interface and are the default type of interface for EJBs. This means that you can omit the @Local annotation and the interface will still be treated as a local interface. Note that in EJB 3.1 it’s not necessary to define a local interface. You can’t define a bean interface at all; instead, you access the bean by its implementation class directly.

ESTA ANOTACION DE TIPO DE EJB3 PERMITE QUE UN SESSION BEAN SEA ACCESIBLE POR MEDIO DE RMI.

@Remote

¿QUE CONDICION DEBEN CUMPLIR LOS PARAMETROS Y TIPOS DE RETORNO DE LOS METODOS DE UNA INTERFAZ DE NEGOCIO REMOTA Y POR QUE?

Remote business interfaces have one special requirement: all parameters and return types of the interface methods must be Serializable. This is because only Serializable objects can be sent across the network using RMI.

¿QUE TECNOLOGIAS DE WEB SERVICE ESTAN SOPORTADAS EN JAVA EE 7?

In Java EE 7 two different web service technologies are supported: SOAP via
JAX-WS and REST via JAX-RS. With both JAX-WS and JAX-RS, annotations can be placed
either on a separate interface or on the bean implementation class itself.

ESTA ANOTACION ES PARA EXPONER UN STATELESS BEAN COMO UN WEB SERVICE BASADO EN SOAP. PROPORCIONE UN EJEMPLO.

For traditional SOAP-based web services, Java EE 6 includes JAX-WS. Like JAX-RS,
JAX-WS uses annotations. To expose an existing stateless bean as a web service, simply create a new interface and add the @javax.jws.WebService annotation. The following code snippet demonstrates this for the BidService:

@WebService
public interface BidSoapService {
List getBids(Item item);
}

¿QUE VENTAJA SE OBTIENE AL TENER UNA INTERFAZ SEPARADA PARA EXPONER UN STATELESS BEAN COMO UN WEB SERVICE BASADO EN SOAP CON LA ANOTACION @WEBSERVICE?

It’s possible to selectively hide methods you don’t want to expose via web services. The ommited methods are not available via SOAP web services. They’re still available via the local and remote interfaces.

DESCRIBA EL CICLO DE VIDA DE UN STATELESS BEAN. ¿QUE ESTADOS LO COMPONEN?

The stateless session bean lifecycle has three states: doesn’t exist, idle, or busy. As a result, there are only two lifecycle callbacks corresponding to bean creation and destruction

DESCRIBA EL PROCESO QUE LLEVA A CABO EL CONTENEDOR PARA ATENDER A UN CLIENTE DE UN STATELESS BEAN

1 Creates bean instances using the default constructor.
2 Injects resources such as JPA providers and database connections.
3 Put instances of the bean in a managed pool (if the container supports pooling).
4 Pulls an idle bean out of the pool when an invocation request is received from the client. At this point, the container may have to instantiate additional beans to handle additional requests. If the container doesn’t support pooling, bean
instances are simply created on demand.
5 Executes the requested business method invoked through the business interface by the client.
6 When the business method finishes executing, the bean is placed back in the “method-ready” pool (if the container supports pooling). If the container doesn’t support pooling, the bean is discarded.
7 As needed, the container retires beans from the pool.

¿COMO SE LOGRA QUE UN STATELESS SESSION BEAN ES COMPLETAMENTE THREAD SAFE?

The stateless session bean lifecycle ensures that all bean instances are accessed only by one request thread at a time. This is why stateless session beans are completely thread-safe and you don’t have to worry about synchronization concerns at all, even though you’re running in a highly concurrent server environment.

¿CUALES SON LOS CALLBACKS DE UN CICLO DE VIDA DE UN STATELESS SESSION BEAN?

A stateless session bean has two callbacks with the following annotations:
■ @PostConstruct—This is invoked immediately after a bean instance is created and set up and all resources are injected.
■ @PreDestroy—This is invoked right before the bean instance is retired

¿EN QUE MOMENTOS DEL CICLO DE VIDA DE UN STATELESS SESSION BEAN SE EJECUTAN LOS CALLBACKS @POSTCONSTRUCT Y @PREDESTROY?

A stateless session bean has two callbacks with the following annotations:
■ @PostConstruct—This is invoked immediately after a bean instance is created and set up and all resources are injected.
■ @PreDestroy—This is invoked right before the bean instance is retired

¿POR QUE NO SE PUEDE USAR EL CONSTRUCTOR EN LUGAR DE UN METODO @POSTCONSTRUCT EN UN STATELESS SESSION BEAN?

When the constructor is instantiated none of the resources have been injected yet, so all of the references will be null.

¿POR QUE NO SE RECOMIENDA USAR FINALIZE() EN LUGAR DE UN METODO @PREDESTROY EN UN STATELESS SESSION BEAN?

The use of the finalize method is actively discouraged and it’s meant more for closing out low-level resources such as JNI references. It’s never to be used for closing out database connections. The finalize method is invoked long after the bean has left the pool and is in the process of being garbage collected.

MENCIONE LAS MEJORES PRACTICAS PARA USAR STATELESS SESSION BEANS EFECTIVAMENTE

TUNE POOLING
DON’T ABUSE REMOTING
USE INTERFACES
PROPERLY DESIGN REMOTE INTERFACES
REMOTE OBJECTS AREN’T PASSED BY REFERENCE
AVOID FINE-GRAINED REMOTE CALLS

¿EN QUE CONSISTE LA MEJOR PRACTICA DE STATELESS BEAN: TUNE POOLING?

Generally, the defaults of most application servers are good enough, but tuning can truly optimize your application and prime it for performance under pressure. The importance of taking advantage of the EJB monitoring features built into most application servers also can’t be understated. Making use of monitoring will truly help you understand the runtime patterns of your application.

¿EN QUE CONSISTE LA MEJOR PRACTICA DE STATELESS BEAN: DON'T ABUSE REMOTING?

Recall that the default interface type is local. While remote interfaces are very useful when they’re needed, they can be a serious performance killer if used otherwise. The issue is that if you accidentally use the @Remote annotation instead of the @Local annotation, you’ll still be able to transparently inject the remote EJB using @EJB as though it were a local EJB without realizing it. This is why it’s very important that you avoid the @Remote annotation unless it’s really needed.

¿EN QUE CONSISTE LA MEJOR PRACTICA DE STATELESS BEAN: USE INTERFACES?

Although it’s technically possible to avoid using interfaces with EJB 3.1, we recommend that you use interfaces anyway unless you’re developing a prototype or using session beans as JSF-backing beans. If you’re developing a service, it’s best to maintain loose coupling through an interface for easier testability as well as future flexibility.

¿EN QUE CONSISTE LA MEJOR PRACTICA DE STATELESS BEAN: PROPERLY DESIGN REMOTE INTERFACES?

When using remote interfaces, make sure the methods that you include in the interface are really supposed to be remotely exposed. You can have a local interface and a remote interface that expose completely different methods.

¿EN QUE CONSISTE LA MEJOR PRACTICA DE STATELESS BEAN: REMOTE OBJECTS ARENT PASSED BY REFERENCE?

Remote method parameters and return types must be serializable. Furthermore, objects are exchanged by copying over the network. This means that you can’t pass an object to a remote stateless method and expect your local reference to mirror changes made by the method. For example, if you pass a list of objects to a remote stateless session bean, you won’t see any changes made to the list unless it’s returned by the remote method. Although this may work for beans being accessed locally in the same application and Java Virtual Machine (JVM), this obviously doesn’t work for remote beans.

¿EN QUE CONSISTE LA MEJOR PRACTICA DE STATELESS BEAN: AVOID FINE-GRAINED REMOTE CALLS? PROPORCIONE UN EJEMPLO

Remote calls are expensive—beans accessed locally can be finer grained, whereas remote beans should naturally be very coarse-grained. On a remote service you want to avoid repeatedly contacting the server for different bits of information to fulfill a request because each call exacts a charge that in aggregate might be unacceptable.
For example, if the user interface (UI) provided a UI that enabled multiple bids to be cancelled, it wouldn’t make sense to call the BidService.cancel() method in a loop— that would be horribly inefficient. Instead you should add an additional method that takes a list of bids to be cancelled.

¿EN QUE TIPO DE PROCESOS DE NEGOCIO SE RECOMIENDA HACER USO DE UN STATEFUL SESSION BEAN? PROPORCIONE UN EJEMPLO.

Stateful session beans are ideal for multistep, workflow-oriented business processes. Example: Wizard workflows.

¿QUE OTRAS ALTERNATIVAS EXISTEN EN LUGAR DE USAR UN STATEFUL SESSION BEAN PARA UN PROCESO DE PASOS MULTIPLES?

Multistep, workflow-oriented business processes don’t necessarily require stateful session beans. For example, you can use plain CDI managed beans at the web tier to manage state. CDI and JSF have a rich set of scopes that’s unmatched in EJB. As a rule of thumb, you should use stateful session beans if your workflow contains business logic that’s not appropriate for the web tier.

REGLA PARA PARA HACER USO DE UN STATEFUL SESSION BEAN COMO SOLUCION A UN PROCESO MULTIPASO O DE FLUJO DE TRABAJO

Given that you can use plain CDI managed beans at the web tier to manage state, as a rule of thumb you should use stateful session beans if your workflow contains business logic that’s not appropriate for the web tier.

¿QUE PRESTACIONES OFRECEN LOS STATEFUL SESSION BEANS?

Like other EJBs, stateful session beans bring a few important features to the table. Stateful session beans are thread-safe and participate in transactions as well as container security. Stateful session beans can also be accessed remotely via RMI and SOAP as well as REST. Finally, the container manages them for you—stateful session beans are automatically passivated when no longer in use or destroyed after an in-activity timeout is triggered. Many of the same reasons for using stateless session beans also apply to stateful session beans.

¿QUE ES LA PASIVACION, EN QUE TIPO DE EJBs SE UTILIZA Y QUIEN LO REALIZA?

Passivation means moving a bean instance from memory to disk. The container accomplishes this task by serializing the entire bean instance

¿QUE ES LA ACTIVACION Y EN QUE TIPO DE EJBs SE UTILIZA Y QUIEN LO REALIZA?

Activation is the opposite of passivation and is done when the bean instance is needed again. The container activates a bean instance by retrieving it from permanent storage and deserializing it.

¿QUE REQUISITOS APLICAN SOBRE UN BEAN PARA PODER SER PASIVADO/ACTIVADO?

All bean instance variables must either be a Java primitive, implement java.io.Serializable, or be marked as transient.

LA PASIVACION NO ES UN REQUISITO DE LA ESPECIFICACION DE EJB. CIERTO O FALSO

True. Just like pooling, passivation isn’t mandated by the EJB specification. But most application servers support passivation. Just like pooling, it’s possible to tune and monitor stateful session bean passivation.

LAS CARACTERISTICAS DE POOLING SON DICTADAS POR LA ESPECIFICACION DE EJB. CIERTO O FALSO

False.

¿QUE ES CLUSTERING DE STATEFUL SESSION BEANS Y EN QUE CONSISTE?

Although the EJB specification doesn’t require it, most application servers cluster stateful session beans. This means that the state of the bean is replicated across all machines participating in the application server cluster. Even if the machine that your stateful session bean currently resides in crashes, a clustered, load-balanced, and failed-over set of servers means that you’ll be transparently rerouted to the next available machine on the cluster and it’ll still have the up-to-date state of the bean. Clustering is an essential feature for mission-critical systems that must guarantee reliability.

EL SOPORTE DE CLUSTERING DE STATEFUL SESSION BEANS POR PARTE DE LOS APP SERVERS ES UN REQUISITO DE LA ESPECIFICACION DE EJB. CIERTO O FALSO

False. Although the EJB specification doesn’t require it, most application servers cluster
stateful session beans.

¿CUALES SON LAS ANOTACIONES RELACIONADAS CON LA ACTIVACION Y LA PASIVACION DE UN STATEFUL SESSION BEAN? ¿CON QUE OTRAS ANOTACIONES SE UTILIZAN EN ALGUNOS CASOS?

@PostActivate y @PrePassivate. They are sometimes used with methods annotated with @PostConstruct and @PreDestroy.

¿QUE RESTRICCION Y DIFERENCIA PRESENTAN LOS STATEFUL SESSION BEANS VS STATELESS CON RESPECTO A INVOCACIONES REMOTAS Y POR QUE?

Specifying stateful session bean business interfaces works in almost exactly the same way as it does for stateless beans, with a couple of exceptions. Stateful session beans support local and remote invocations through the @Local and @Remote annotations. But a stateful session bean can’t have a web service endpoint interface. This means that a stateful session bean can’t be exposed using JAX-RS or JAX-WS. This is because web service interfaces are inherently stateless in nature. A business interface should always include a @Remove annotated method. Multiple methods can have this annotation.

HAGA UN DIAGRAMA DEL CICLO DE VIDA DE UN STATELESS BEAN

DESCRIBA EL CICLO DE VIDA DE UN STATEFUL BEAN

The container follows these steps:
1 The container always creates a new bean instance using the default constructor
whenever a new client session is started.
2 After the constructor has completed, the container injects the resources such as
JPA contexts, data sources, and other beans.
3 An instance is stored in memory awaiting method invocations.
4 A client executes a business method through the business interface.
5 The container waits for subsequent method invocations and executes them.
6 If the client remains idle for a period of time, the container passivates the bean
instance (if the container supports passivation). The bean gets serialized out to disk.
7 If the client invokes a passivated bean, it’s activated (the object is read in from disk).
8 If the client doesn’t invoke a method on the bean for a period of time, the bean
is destroyed.
9 If the client requests removal of a bean instance and it’s presently passivated,
it’ll be activated, and then the bean will be destroyed and reclaimed by garbage collection

¿QUE ANOTACION DEBE SER SIEMPRE INCLUIDA EN UN METODO DE NEGOCIO DE UN STATEFUL SESSION BEAN Y POR QUE?

A business interface should always include a @Remove annotated method. Multiple methods can have this annotation.

¿CUALES SON LOS CALLBACK METHODS DE UN STATEFUL SESSION BEAN? ¿QUE DIFERENCIA HAY CON RESPECTO A STATELESS Y POR QUE?

The callbacks available on stateful session beans are as follows:
■ @PostConstruct—This is invoked right after the default constructor has executed and resources have been injected.
■ @PrePassivate—This is invoked before a bean is passivated; that’s before the bean is serialized out to disk.
■ @PostActivate—This is invoked after a bean has been read back into memory but before business methods are invoked from a client.
■ @PreDestroy—This is invoked after the bean’s timeout has expired or the client has invoked a method annotated with @Remove. The instance will be subsequently released to the garbage collector.

¿QUE PRACTICA ES COMUNMENTE ENCONTRADA EN EL USO DE LAS ANOTACIONES DE CALLBACKS DEL CICLO DE VIDA DE UN STATEFUL BEAN?

The callback annotations may be placed on multiple methods—you’re not limited to one per class. Most often the prepassivation step consists of releasing heavy-duty resources like open databases, messaging, and socket connections that can’t be serialized. A wellbehaved bean should ensure that heavy-duty resources are both closed and explicitly set to null before the actual passivation (serialization) takes place. From the perspective of a bean instance, there isn’t much of a difference between being passivated and being destroyed. Very often one method is annotated with both the @PrePassivate and @PreDestroy annotations. The same thing is often done for @PostConstruct and @PostActivate. In the case of both of these annotations, heavyduty resources are being either established or reestablished. One caveat: you’re not responsible for reestablishing connections of injected resources. When a bean is activated, the container will reinject all of the resources.

¿COMO SE LE INDICA AL CONTENEDOR POR PARTE DEL CLIENTE QUE YA NO NECESITA UN STATEFUL BEAN? ¿POR QUE ES IMPORTANTE HACERLO?

In addition to the callbacks, one or more methods can be annotated with @Remove. This annotation informs the container that when the method exits, the stateful session bean is to be released. The client no longer needs and will no longer access the stateful session bean. If the client attempts to access the bean afterward, an exception will
be thrown. Failure to remove stateful beans will have a serious impact on server performance. The problem might not be apparent with a small number of clients, but it will become critical as more people request stateful session beans over time.

¿CUALES SON LAS MEJORES PRACTICAS CON RESPECTO DE LOS STATEFUL BEANS?

CHOOSING SESSION DATA APPROPRIATELY
TUNING PASSIVATION
REMOVE STATEFUL SESSION BEANS

¿EN QUE CONSISTE LA MEJOR PRACTICA DE STATEFUL SESSION BEANS: CHOOSING SESSION DATA APPROPRIATELY?

Stateful session beans can become resource hogs and cause performance problems if they’re not used properly. Because the container stores session information in memory, if you have thousands of concurrent clients for your stateful session bean, you may run out of memory or cause excessive disk thrashing as the container passivates and
activates beans. Consequently, you have to closely examine what kind of data you’re storing in the conversation state and make sure the total memory footprint for the stateful bean is as small as possible. For example, be careful of storing objects with very deep dependency graphs, byte arrays, or character arrays.
If you cluster stateful session beans, the conversational state is replicated between different instances of the EJB container. State replication uses network bandwidth. Storing a large object in the bean state may have a significant impact on the performance of your application because the container will spend an excessive amount of time replicating objects to other instances to ensure high availability.

¿EN QUE CONSISTE LA MEJOR PRACTICA DE STATEFUL SESSION BEANS: TUNING PASSIVATION?

The rules for passivation are generally implementation-specific. Improper use of passivation policies (when passivation configuration is an option) may cause performance problems. For example, the Oracle Application Server passivates bean instances when the idle time for a bean instance expires, when the maximum number of active bean instances allowed for a stateful session bean is reached, and when the threshold for JVM memory is reached. You have to check the documentation for your EJB container and appropriately set passivation rules. For example, if you set the maximum number of active instances allowed for a stateful session bean instance to 100 and you usually have 150 active clients, the container will continue to passivate and activate bean instances, thus causing performance problems.

¿EN QUE CONSISTE LA MEJOR PRACTICA DE STATEFUL SESSION BEANS: REMOVE STATEFUL SESSION BEANS?

You can go a long way toward solving potential memory problems by explicitly removing the bean instances that are no longer required rather than depending on the container to time them out. Thus, each stateful session bean should have at least one method annotated with @Remove and then invoke this method at the end of the bean’s workflow.
Now that you have a handle on stateful session beans, let’s delve into singleton beans.

DESCRIBA EN QUE CONSISTEN LOS SINGLETON SESSION BEANS

Singleton session beans were added in EJB 3.1. As their name suggests, only one instance is created during the lifecycle of an enterprise application. Thus, all clients access the same bean, as shown in figure 3.10. Singleton beans solved two architectural problems that had long plagued Java EE applications: how to initialize at server startup and also have only a single instance of a bean. Solutions prior to EJB 3.1 involved the use of “startup servlets” or JCA connectors. Countless applications undoubtedly violated the Java EE specification and used static variables or nonmanaged objects. At best these were inelegant solutions, but many solutions were undoubtedly unsound.
Singleton session beans are very similar to stateless session beans. Singleton beans support the same callbacks as stateless session beans but come with some unique features, including the ability to control concurrent access to the bean as well as the ability to chain singleton bean instantiation. Chaining instantiation means that one bean
can depend on another bean. As already mentioned, singleton beans can be marked to start when the application is deployed with the added semantics that application launch isn’t complete until the startup beans have successfully completed. Just like stateless and stateful beans, singleton beans also support injection, security, and transaction management.

¿COMO SE DECLARA QUE UN BEAN ES SINGLETON?

With the @Singleton annotation.

¿EN QUE CONSISTE EL ENCADENAMIENTO DE INSTANCIACION? ¿CON QUE TIPO DE SESSION BEAN SE UTILIZAN?

Chaining instantiation means that one bean can depend on another bean. As already mentioned, singleton beans can be marked to start when the application is deployed with the added semantics that application launch isn’t complete until the startup beans have successfully completed. It is used on singleton session beans.

MENCIONE Y DESCRIBA TAREAS COMUNES PARA LOS CUALES SON APROPIADOS LOS SINGLETON BEANS.

STARTUP TASKS
CENTRALIZED CLEARINGHOUSE
COUNTERPOINT

DESCRIBA LA TAREA COMUN PARA SINGLETON BEANS: STARTUP TASKS.

Very often when an application is deployed, you want to perform a couple of operations before the application is accessible to external users and other systems. When the application starts up, you may want to check the database for consistency or verify that an external system is up and running. Very often there are race conditions with startup processes—although LDAP might be configured to start before GlassFish, GlassFish might successfully deploy an application before LDAP is ready to accept connections. A singleton bean marked annotated to launch on startup could repeatedly poll for LDAP and thus ensure that the application isn’t accessible until all of the external services are ready to accept connections.

DESCRIBA LA TAREA COMUN PARA SINGLETON BEANS: CENTRALIZED CLEARINGHOUSE

Although centralized chokepoints are the anathema to writing scalable software, there are times when this is necessary. Perhaps the bean is interacting with a legacy system that’s limited in its connectivity. More likely you’ll have situations where you want to cache a value once and control its value while making it available to multiple clients.
With the concurrency control, you can enable concurrent reads while enforcing synchronization on the writes. So, for instance, you may want to cache a value in memory so that each web visit results in a database hit.

DESCRIBA LA TAREA COMUN PARA SINGLETON BEANS: COUNTERPOINT

Singleton session beans should be used to solve problems that call for a singleton and require services of the container. For example, a singleton bean shouldn’t be used to implement logic that verifies a phone number. That doesn’t need to be a singleton nor does it require any services from a container. It’s a utility method. If the bean isn’t caching or guarding state from concurrent access or modification, then it shouldn’t be a singleton session bean. Because singleton beans can be a bottleneck if used incorrectly, a large application should be weighted primarily toward stateless session beans, some stateful session beans, and a handful of singleton beans if necessary.
You should never use singletons as stateless services; rather, use stateless session beans instead. Most stateless services aren’t read-only and require database interaction through non-thread-safe APIs like the JPA entity manager. Using a thread-safe singleton in such a case doesn’t scale because there’s only one instance of a bean that must be shared by all concurrent clients. Now that you have a basic grasp of singleton session beans, let’s dive into a code example.

¿CUAL ES LA DISTRIBUCION DE SESSION BEANS CONSIDERADA APROPIADA PARA UN BUEN DISEÑO DE SISTEMA EMPRESARIAL?

Large application should be weighted primarily toward stateless session beans, some stateful session beans, and a handful of singleton beans if necessary.

¿CUAL ES LA PRINCIPAL DIFERENCIA EN UNA BUSINESS INTERFACE DE UN SINGLETON SESSION BEAN VS. STATELESS? ¿QUE ANOTACIONES SE PUEDEN UTILIZAR PARA UN SINGLETON? ¿QUE REQUISITO PRESENTAN PARA FUNCIONAR?

Singleton session beans have the same business interface capabilities as stateless session beans. You can have remote, local, and web service (both SOAP and REST) business interfaces. Each of these three methods of accessing a singleton session bean is denoted using the annotations @Local, @Remote, and @WebService, respectively.
The only real difference between singleton and stateless session bean business interfaces is that you can annotate a singleton session bean interface’s methods with the following annotations:
■ @Lock(LockType.READ)
■ @Lock(LockType.WRITE)
■ @AccessTimeout
All three of these annotations have an effect only if container-managed concurrency is being used; otherwise they have no effect. It’s possible that the web service interface specifies different concurrency behavior than the local interface (although this is unlikely). As is the case with both stateless and stateful session beans, it isn’t necessary
to provide a local interface.

DESCRIBA EL CICLO DE VIDA DE UN SINGLETON SESSION BEAN.

The lifecycle of singleton session beans is the simplest of all of the beans. Once they’re instantiated, they’re not destroyed until the application terminates. Complexity in their lifecycle comes into play only if there are dependencies between beans. During application deployment, the container iterates over the singleton beans checking for
dependencies. In addition, a bean can also be marked to auto-instantiate on application deployment. This enables business logic to auto-execute when an application is started. Let’s start by looking at the lifecycle in figure 3.12:
1 The container starts by creating a new instance of the singleton bean. The bean may be instantiated on startup (@Startup) or as a result of another bean being instantiated (@DependsOn). Normally, beans are instantiated lazily as they’re first accessed.
2 After the constructor has completed, the container injects the resources such as JPA contexts, data sources, and other beans.
3 The @PostConstruct annotated method is invoked. The bean isn’t accessible until it completes successfully.
4 The instance is stored in memory awaiting method invocations.
5 The client executes a business method through the business interface.
6 The container is informed that it must shut down.
7 The @PreDestroy callback is invoked prior to the application terminating

¿PARA QUE Y COMO SE UTILIZA LA ANOTACION @DependsOn? ¿EN QUE TIPOS DE BEAN SE PUEDE UTILIZAR?

A singleton bean may be annotated with a @DependsOn annotation. This annotation enables a bean to depend on another bean. When a bean is instantiated, any of its dependencies will also be instantiated. The expectation is that when a bean depends on another bean, that other bean will have done something to set the state of
the application.
This annotation is placed on the bean class and takes one or more names of singleton session beans that must be instantiated first. The order of the dependencies in the list isn’t maintained—this means that if a bean is annotated with @DependsOn(A,B) , you can’t depend on A being instantiated before B. B should have its own @DependsOn
annotation and specify that it expects A to be instantiated. The @DependsOn annotation ties nicely into the @Startup annotation.

¿CUALES SON LAS MEJORES PRACTICAS PARA UTILIZAR UN SINGLETON SESSION BEAN DE FORMA EFECTIVA?

CHOOSING CORRECT CONCURRENCY TYPE
CONFIGURING CONTAINER-MANAGED CONCURRENCY
MANAGING STARTUP SINGLETONS
HANDLING EXCEPTIONS

DESCRIBA LA MEJOR PRACTICA PARA SINGLETON SESSION BEAN: CHOOSING CORRECT CONCURRENCY TYPE.

When you create a new singleton bean, one of the most important decisions is choosing the correct concurrency type for your bean. For the vast majority of beans, containermanaged concurrency makes the most sense. With container-managed concurrency, you’re delegating synchronization to the container. The container gives you the option of marking methods either @Lock(LockType.READ) or @Lock(LockType.WRITE) . A lock type of READ enables multiple threads to access the bean concurrently, whereas the WRITE lock grants exclusive access. If you go with the bean-managed approach, it’s up to you to manage concurrent access via synchronized, volatile, and other Java constructs. This approach makes sense if you require finer-grained locking than simply read–write locks. Alternatively, if you’re storing and retrieving data from a concurrent HashMap, you won’t need the container concurrency features.

DESCRIBA LA MEJOR PRACTICA PARA SINGLETON SESSION BEAN: CONFIGURING CONTAINER-MANAGED CONCURRENCY.

One of the dangers with container-managed concurrency is that the container by default uses the write lock if you don’t specify otherwise. The write lock limits access to the class to only one method at a time. Each business method in the class is effectively marked with the synchronized keyword. This will adversely affect performance of the
singleton—only one client will be serviced at a time. If a request takes one second to service, then 1,000 clients will result in a total wait of about 17 minutes. The wait times per client will vary—some will have one second whereas others might wait for a bit longer. A singleton thus needs to be divided into write (@Lock(LockType.WRITE) ) and read (@Lock(LockType.READ) ) methods. The write method updates data and thus requires the exclusive lock. The read method doesn’t require an exclusive lock and thus multiple clients can concurrently access the data. If a write method may take a long time, it should be annotated @AccessTimeout if you don’t want the code waiting for an indeterminate amount of time. This annotation can also be used to enforce a certain level of service—if the method is taking too long, an exception raising the method as a problem can go a long way toward resolving performance issues.

DESCRIBA LA MEJOR PRACTICA PARA SINGLETON SESSION BEAN: MANAGING STARTUP SINGLETONS.

Startup singletons can be used to auto-run business logic on application startup and cache data for the application. A singleton class marked with the startup annotation will be instantiated during application deployment. It must be stressed that this is during application deployment. Containers, such as GlassFish, will throw a java.lang
.IllegalAccessException if your bean tries to access a stateless/stateful session bean from the @PostConstruct method. So other beans may not be available yet, but you’ll have access to JPA and can manipulate the database. If multiple startup beans are used, the @DependsOn annotation should be used to control the startup sequence.
Without the @DependsOn annotation, there’s no guarantee that the singleton will be instantiated—a changing random order should be assumed. It’s also important that you don’t create circular dependencies of startup singletons.

DESCRIBA LA MEJOR PRACTICA PARA SINGLETON SESSION BEAN: HANDLING EXCEPTIONS.

Exceptions generated from a singleton bean are treated differently than exceptions from a stateless or stateful session bean. An exception thrown from the PostConstruct method of a singleton causes the instance to be discarded. If the exception is thrown from the PostConstruct method of a startup bean, the application server may choose not to deploy the application. An exception thrown by a business method doesn’t result in the bean being discarded—the bean will be discarded only when the application terminates. What this means is that your application logic should take this into account. Also, because a singleton bean is in existence for the entire life of the application, you might have to take care when dealing with external resources. If the application is left running for weeks, you must take care to ensure that there’s appropriate error handling and recovery code in place. If the bean opens up a socket connection to another system, at some point that socket connection will be closed—watch out for time-outs

¿EN QUE CASOS TIENE SENTIDO UTILIZAR BEAN MANAGED CONCURRENCY VS CONTAINER-MANAGED EN UN SINGLETON BEAN?
¿QUE DIFERENCIA EXISTE ENTRE LOS METODOS DE UN SINGLETON BEAN CON LOCKS DE TIPO READ VS WRITE? EN QUE CASOS SE RECOMIENDA UTILIZAR CADA UNO?

DESCRIBA LAS MEJORES PRACTICAS AL CONFIGURAR UN SINGLETON SESSION BEAN CON CONTAINER MANAGED CONCURRENCY.

¿PARA QUE CASOS SE PUEDE UTILIZAR LA ANOTACION @ACCESSTIMEOUT EN UN SINGLETON SESSION BEAN?
¿QUE SUCEDE SI UNA EXCEPCION ES ARROJADA DE UN METODO @POSTCONSTRUCT DE UN SINGLETON SESSION BEAN? ¿QUE PODRÍA SUCEDER SI EL SINGLETON ESTA ANOTADO CON @STARTUP?
¿QUE TIPOS DE SESSION BEANS PUEDEN SER ANOTADOS CON @ASYNCHRONOUS?

New to EJB 3.1 is support for asynchronous beans with the @Asynchronous annotation. This isn’t a new type of session bean but rather a new functionality that you can use with stateless, stateful, and singleton session beans.

¿QUE FUNCIONALIDAD QUE OTORGA LA ANOTACION @ASYNCHRONOUS?

This new functionality enables methods invoked by the client on methods contained in the business interface to be executed asynchronously on a separate thread. Prior to this, the only avenue for parallelization in Java EE was via MDBs. Using and coordinating activities between MDBs and stateless/stateful session beans is a pretty heavyweight solution that for simple tasks is overkill and adds unnecessary complexity.
The title asynchronous session beans is somewhat of a misnomer. The beans aren’t asynchronous in themselves; rather, their methods are asynchronous. With the @Asynchronous annotation, a method or an entire class can be marked as being asynchronous. When an asynchronous method or method on an asynchronous class is invoked, the container spawns a separate thread for execution.

¿CUALES SON LOS PATRONES DE USO DE UN METODO ASINCRONO? ¿COMO SE RELACIONAN SUS TIPOS DE RETORNO?

An asynchronous method is just like any other business method on a bean class—it can return a value, throw exceptions, and accept parameters. The return type for an asynchronous method is either void or java.util.concurrent.Future. This enables two usage patterns: fire and forget (using void) or fire and check back later for an answer (Future). Only methods with a declared return type of Future can declare an exception. If an exception is thrown by the asynchronous method, the exception will be caught and rethrown when get() is called on the Future object. The original exception will be wrapped in an ExecutionException. Runtime exceptions thrown by an asynchronous method with no return type will be lost and the original caller will not be notified.

¿QUE RESTRICCIONES SE PRESENTAN CON RESPECTO DE LAS EXCEPCIONES QUE PUEDE ARROJAR UN METODO ASINCRONO? DESCRIBA SU FUNCIONAMIENTO.

One important caveat of asynchronous method invocation is that transactions aren’t propagated to the asynchronous method—a new transaction will be started for the asynchronous method. But unlike transactions, the security principle will be propagated.
When an asynchronous method is invoked, the call returns to the client before the method is invoked on the bean. If no value is returned from the method (the return type is void) , the operation is a fire-and-forget task from the perspective of the client. If you might need the result of asynchronous processing or might have to potentially cancel the operation, a Future object should be returned by the business method. In both circumstances, the execution proceeds on a separate thread. This is incredibly powerful; the next section will explain the ground rules for when and where you should add asynchronous processing to an application.

¿QUE SUCEDE CON UNA OPERACION QUE INVOCA UN METODO ASINCRONO, TENIENDO UNA TRANSACCION EN CURSO?

¿EN QUE CIRCUNSTANCIAS SE DEBERÁN IMPLEMENTAR METODOS ASINCRONOS?

Asynchronous session beans should be used only under two circumstances:
■ You have a long-running operation that you want to start and then continue something else, regardless of what happens with this operation.
■ You have a long-running operation for which you want to start and then check back later to see what the result is after doing something. You may also want to cancel this operation
Prior to EJB 3.1, the only way to do either of these was to multithread your client. Because the container controlled concurrency, there was no way to notify a bean that a long-running operation should be cancelled. Remember, the container controls concurrency, so each method was synchronized on the bean, meaning that only one thread could invoke a method at a time. EJB 3.1 is thus a point release with additional major functionality.
Asynchronous session beans are intended to be lightweight, so they don’t provide any reliability guarantees. This means that if a container crashes while an asynchronous method is getting executed, the method won’t recover. Asynchronous beans are also not loosely coupled, which means that a client holds a direct reference to the asynchronously invoked session bean. If you require reliability and loose coupling and not just asynchronous processing, you should consider message-driven beans.

¿QUE SE PUEDE HACER CON LA INTERFAZ FUTURE Y EN QUÉ CASOS SE UTILIZA?

Unless your method is a fire and forget, you’ll probably be interested in the results of the method call. To work with results from an asynchronous method, you must return an object implementing the java.util.concurrent.Future interface. The Future interface has the following methods:
■ boolean cancel(boolean mayInterruptIfRunning) —This cancels the operation.
■ V get() —This returns the value and blocks until the result is available.
■ V get(long timeout, TimeUnit unit) —This returns the result or null if the result isn’t available in the specified time limit.
■ boolean isCancelled() —This returns true if this task was cancelled.
■ boolean isDone() —This returns true if the task has completed.
■ With the Future interface you can do the following tasks:
– Cancel the operation.
– Retrieve the value of the computation, optionally with a time-out if you don’t want to wait.
– Check to see if the operation has either been cancelled or has completed

DESCRIBA LAS CONSIDERACIONES A TENER PARA USAR UN SESSION BEAN ASINCRONO DE FORMA EFECTIVA.

The @Asynchronous annotation is very powerful and potentially dangerous. Using this annotation too liberally will have a detrimental impact on performance. Threads have a large resource footprint and thus there’s an upper limit to the number of threads. Either the limit may be operating system-dependent or the application container may
limit the number of threads via a thread pool. In either case, hitting the upper limit has negative consequences. Thus, this functionality should be used where it’s truly needed. Pay special attention to thread leaks—if threads fail to terminate, they may loiter until the application terminates. There are two more important considerations
with asynchronous methods: supporting cancel and handling exceptions.
SUPPORTING CANCEL
HANDLING EXCEPTIONS

DESCRIBA LA MEJOR PRACTICA DE BEANS ASINCRONOS: SUPPORTING CANCEL

Asynchronous tasks that return results should support the cancel operation. Supporting cancel enables clients to terminate the operation at their discretion. This is especially important if the operation is long running. Within an asynchronous bean method, the wasCancelCalled() method on the SessionContext will report if the client, via the
Future object, has requested the operation to be terminated. This method should be checked within a loop and before blocking operations are called.

DESCRIBA LA MEJOR PRACTICA DE BEANS ASINCRONOS: HANDLING EXCEPTIONS

If an asynchronous task doesn’t return a Future instance to a client, and the client never calls get() on the Future object, the client will never know if an asynchronous method failed. This approach should only be taken if the asynchronous operation is optional. Optional means that it doesn’t matter if the method runs, succeeds, or fails. In a situation where it’s necessary to know if the operation succeeded or if it failed, a Future object should be returned and the client code should check it and act upon the error. Remember, if you’re using the fire-and-forget approach, the only way to find out if an asynchronous method failed is to look at the log file for the application server.

¿QUE CONSIDERACION SE DEBE TENER CON RESPECTO A LOS SESSION BEAN ASINCRONOS Y EL MANEJO DE HILOS POR PARTE DEL SO O DEL CONTENEDOR?

¿COMO SE PUEDE SABER SI UN METODO ASINCRONO BAJO EL ESQUEMA FIRE-AND-FORGET ARROJÓ UNA EXCEPCION?

The only way to find out if an asynchronous method failed is to look at the log file for the application server.