Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

101.

What Is The Main Functionality Of The Remote Reference Layer ?

Answer»

RRL exists in both the RMI CLIENT and server. It is used by the stub or SKELETON protocol layer and USES the transport layer. RRL is reponsible for transport-independent functioning of RMI, such as connection management or unicast/multicast OBJECT invocation.

RRL exists in both the RMI client and server. It is used by the stub or skeleton protocol layer and uses the transport layer. RRL is reponsible for transport-independent functioning of RMI, such as connection management or unicast/multicast object invocation.

102.

Explain Lazy Activation?

Answer»

LAZY activation: This MEANS that the ACTIVABLE remote object will be activated by rmid (default). This activation is performed only when the first remote METHOD call is intercepted.

Lazy activation: This means that the activable remote object will be activated by rmid (default). This activation is performed only when the first remote method call is intercepted.

103.

Does Rmi-iiop Support Dynamic Downloading Of Classes?

Answer»

No, RMI-IIOP doesn't support dynamic downloading of the classes as it is DONE with CORBA in DII (Dynamic Interface Invocation).Actually RMI-IIOP combines the USABILITY of Java REMOTE Method Invocation (RMI) with the interoperability of the Internet Inter-ORB PROTOCOL (IIOP).So in order to attain this interoperability between RMI and CORBA,some of the features that are supported by RMI but not CORBA and vice versa are eliminated from the RMI-IIOP specification.

No, RMI-IIOP doesn't support dynamic downloading of the classes as it is done with CORBA in DII (Dynamic Interface Invocation).Actually RMI-IIOP combines the usability of Java Remote Method Invocation (RMI) with the interoperability of the Internet Inter-ORB Protocol (IIOP).So in order to attain this interoperability between RMI and CORBA,some of the features that are supported by RMI but not CORBA and vice versa are eliminated from the RMI-IIOP specification.

104.

How Many Types Of Protocol Implementations Does Rmi Have?

Answer»

RMI has at least three protocol implementations: Java Remote Method Protocol(JRMP), Internet Inter ORB Protocol(IIOP), and Jini Extensible Remote Invocation(JERI). These are alternatives, not part of the same thing, All three are INDEED LAYER 6 protocols for those who are still speaking OSI REFERENCE MODEL.

RMI has at least three protocol implementations: Java Remote Method Protocol(JRMP), Internet Inter ORB Protocol(IIOP), and Jini Extensible Remote Invocation(JERI). These are alternatives, not part of the same thing, All three are indeed layer 6 protocols for those who are still speaking OSI reference model.

105.

Does Rmi-iiop Support Code Downloading For Java Objects Sent By Value Across An Iiop Connection In The Same Way As Rmi Does Across A Jrmp Connection?

Answer»

YES. The JDK 1.2 and above support the dynamic class LOADING.

Yes. The JDK 1.2 and above support the dynamic class loading.

106.

What Are The Services In Rmi ?

Answer»

An RMI "SERVICE" COULD WELL be any Java METHOD that can be invoked remotely. The other service is the JRMP RMI naming service which is a lookup service.

An RMI "service" could well be any Java method that can be invoked remotely. The other service is the JRMP RMI naming service which is a lookup service.

107.

What Is The Difference Between Rmi & Corba ?

Answer»

The most significant difference between RMI and CORBA is that CORBA was made specifically for interoperability across programming languages. That is CORBA fosters the notion that programs can be built to interact in multiple languages. The server could be WRITTEN in C++, the business logic in Python, and the front-end written in COBOL in theory. RMI, on the other hand is a total Java solution, the interfaces, the implementations and the clients--all are written in Java.

RMI ALLOWS dynamic loading of classes at runtime. In a multi-language CORBA environment, dynamic class loading is not POSSIBLE. The important advantage to dynamic class loading is that it allows ARGUMENTS to be passed in remote invocations that are subtypes of the declared types. In CORBA, all types have to be known in ADVANCE. RMI (as well as RMI/IIOP) provides support for polymorphic parameter passing, whereas strict CORBA does not. CORBA does have support for multiple languages which is good for some applications, but RMI has the advantage of being dynamic, which is good for other applications.

The most significant difference between RMI and CORBA is that CORBA was made specifically for interoperability across programming languages. That is CORBA fosters the notion that programs can be built to interact in multiple languages. The server could be written in C++, the business logic in Python, and the front-end written in COBOL in theory. RMI, on the other hand is a total Java solution, the interfaces, the implementations and the clients--all are written in Java.

RMI allows dynamic loading of classes at runtime. In a multi-language CORBA environment, dynamic class loading is not possible. The important advantage to dynamic class loading is that it allows arguments to be passed in remote invocations that are subtypes of the declared types. In CORBA, all types have to be known in advance. RMI (as well as RMI/IIOP) provides support for polymorphic parameter passing, whereas strict CORBA does not. CORBA does have support for multiple languages which is good for some applications, but RMI has the advantage of being dynamic, which is good for other applications.

108.

Normally In The Java Programming Language, It Is Possible To Cast An Interface Instance To An Instance Of The Class From Which It Was Created And Use The Result. Why Doesn't This Work In Rmi?

Answer»

In RMI the CLIENT sees only a stub for the original object. The stub implements only the remote interfaces and their remote METHODS and cannot be cast back to the original implementation CLASS because it's just a stub. So, you cannot PASS a remote object reference from a server to a client, and then send it back to the server and be able to cast it back to the original implementation class. You can, though, use the remote object reference on the server to make a remote call to the object. If you need to find the implementation class again, you'll need to KEEP a table that maps the remote reference to the implementation class.

In RMI the client sees only a stub for the original object. The stub implements only the remote interfaces and their remote methods and cannot be cast back to the original implementation class because it's just a stub. So, you cannot pass a remote object reference from a server to a client, and then send it back to the server and be able to cast it back to the original implementation class. You can, though, use the remote object reference on the server to make a remote call to the object. If you need to find the implementation class again, you'll need to keep a table that maps the remote reference to the implementation class.

109.

Does Rmi Handle "out" And "inout" Parameters (like Corba)?

Answer»

RMI does not support "out" or "INOUT" parameters, just LIKE the rest of the CORE JAVA programming language. All remote calls are methods of a remote object. Local objects are passed by COPY and remote objects are passed by reference to a stub.

RMI does not support "out" or "inout" parameters, just like the rest of the core Java programming language. All remote calls are methods of a remote object. Local objects are passed by copy and remote objects are passed by reference to a stub.

110.

Why Do I Get The Exception "java.net.socketexception: Address Already In Use" When I Try To Run The Registry?

Answer»

This EXCEPTION MEANS that the port that the RegistryImpl uses (by default 1099) is already in use. You MAY have another registry RUNNING on your machine and will need to STOP it.

This exception means that the port that the RegistryImpl uses (by default 1099) is already in use. You may have another registry running on your machine and will need to stop it.

111.

How Do Rmi Clients Contact Remote Rmi Servers?

Answer»

For an RMI client to contact a REMOTE RMI server, the client must FIRST hold a reference to the server. The Naming.lookup method call is the most common mechanism by which clients initially obtain references to remote servers. Remote references may be obtained by other means, for example: all remote method calls can return remote references. This is what Naming.lookup does; it uses a well-known stub to make a remote method call to the rmiregistry, which sends back the remote reference to the object requested by the lookup method. Every remote reference contains a server HOSTNAME and port number that allow clients to locate the VM that is serving a PARTICULAR remote object. Once an RMI client has a remote reference, the client will use the hostname and port provided in the reference to open a socket CONNECTION to the remote server. Please note that with RMI the terms client and server can refer to the same program. A Java program that acts as an RMI server contains an exported remote object. An RMI client is a program that invokes one or more methods on a remote object in another virtual machine. If a VM performs both of these functions, it may be referred to as an RMI client and an RMI server.

For an RMI client to contact a remote RMI server, the client must first hold a reference to the server. The Naming.lookup method call is the most common mechanism by which clients initially obtain references to remote servers. Remote references may be obtained by other means, for example: all remote method calls can return remote references. This is what Naming.lookup does; it uses a well-known stub to make a remote method call to the rmiregistry, which sends back the remote reference to the object requested by the lookup method. Every remote reference contains a server hostname and port number that allow clients to locate the VM that is serving a particular remote object. Once an RMI client has a remote reference, the client will use the hostname and port provided in the reference to open a socket connection to the remote server. Please note that with RMI the terms client and server can refer to the same program. A Java program that acts as an RMI server contains an exported remote object. An RMI client is a program that invokes one or more methods on a remote object in another virtual machine. If a VM performs both of these functions, it may be referred to as an RMI client and an RMI server.

112.

Explain About Rmi And It's Usage?

Answer»

RMI is one of the distributed computing technology alternative powered by Java . RMI stands for Remote Method Invocation ,to keep it SIMPLE it means accessing a service from DIFFERENT node ( i.e., accessing a service provided by an object on server machine , here an object in client JVM talks with object in the server JVM ). Java provides an API and base some classes ( in package java.rmi ) to perform these kind of OPERATIONS . We basically use this methodology when we need to publish an object at server side which exposes set of services ( as methods in Object oriented programming TERMINOLOGY ) and where in one or more clients access these services from remote machines. By this we are distibuting a common code in TWO different JVM's and we are able to access the code on different JVM.

RMI is one of the distributed computing technology alternative powered by Java . RMI stands for Remote Method Invocation ,to keep it simple it means accessing a service from different node ( i.e., accessing a service provided by an object on server machine , here an object in client JVM talks with object in the server JVM ). Java provides an API and base some classes ( in package java.rmi ) to perform these kind of operations . We basically use this methodology when we need to publish an object at server side which exposes set of services ( as methods in Object oriented programming terminology ) and where in one or more clients access these services from remote machines. By this we are distibuting a common code in two different JVM's and we are able to access the code on different JVM.

113.

Explain Rmi Architecture?

Answer»

RMI uses a LAYERED architecture, each of the layers could be enhanced or replaced without affecting the rest of the system. The DETAILS of layers can be summarised as follows: Application LAYER: The client and SERVER program Stub & Skeleton Layer: Intercepts method calls made by the client/redirects these calls to a remote RMI service. Remote Reference Layer: Understands how to interpret and manage references made from clients to the remote service objects. Transport layer: Based on TCP/IP connections between machines in a network. It provides basic CONNECTIVITY, as well as some firewall penetration strategies.

RMI uses a layered architecture, each of the layers could be enhanced or replaced without affecting the rest of the system. The details of layers can be summarised as follows: Application Layer: The client and server program Stub & Skeleton Layer: Intercepts method calls made by the client/redirects these calls to a remote RMI service. Remote Reference Layer: Understands how to interpret and manage references made from clients to the remote service objects. Transport layer: Based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies.

114.

How Do You Optimize Java Message Service (jms)?

Answer»

• Start producer CONNECTION after you start consumer.
USE concurrent processing of MESSAGES.
• Close the Connection when finished.
CHOOSE either DUPS_OK_ACKNOWLEDGE or AUTO_ACKNOWLEDGE rather than CLIENT_ACKNOWLEDGE.
CONTROL transactions by using separate transactional session for transactional messages and non-transactional session for non-transactional messages.
• Close session object when finished.

• Start producer connection after you start consumer.
• Use concurrent processing of messages.
• Close the Connection when finished.
• Choose either DUPS_OK_ACKNOWLEDGE or AUTO_ACKNOWLEDGE rather than CLIENT_ACKNOWLEDGE.
• Control transactions by using separate transactional session for transactional messages and non-transactional session for non-transactional messages.
• Close session object when finished.

115.

How Do You Optimize Message Driven Beans?

Answer»

• Tune the Message driven beans POOL size to PROMOTE concurrent processing of messages.
• Use setMesssageDrivenContext() or ejbCreate() method to CACHE bean specific resources.
RELEASE acquired resources in ejbRemove() method.
• Use JMS tuning TECHNIQUES in Message driven beans.

• Tune the Message driven beans pool size to promote concurrent processing of messages.
• Use setMesssageDrivenContext() or ejbCreate() method to cache bean specific resources.
• Release acquired resources in ejbRemove() method.
• Use JMS tuning techniques in Message driven beans.

116.

How Do You Optimize Entity Beans?

Answer»

• Tune the ENTITY beans pool size to avoid overhead of creation and destruction of beans.
• Tune the entity beans cache size to avoid overhead of activation, passivation and database calls.
• Use setEntityContext() METHOD to cache BEAN SPECIFIC resources.
• Release acquired resources in unSetEntityContext() method.
• Use Lazy loading to avoid unnecessary pre-loading of child data.
• Choose optimal transaction isolation level to avoid blocking of other TRANSACTIONAL clients.
• Use proper locking strategy.
• Make read-only entity beans for read only operations.

• Tune the entity beans pool size to avoid overhead of creation and destruction of beans.
• Tune the entity beans cache size to avoid overhead of activation, passivation and database calls.
• Use setEntityContext() method to cache bean specific resources.
• Release acquired resources in unSetEntityContext() method.
• Use Lazy loading to avoid unnecessary pre-loading of child data.
• Choose optimal transaction isolation level to avoid blocking of other transactional clients.
• Use proper locking strategy.
• Make read-only entity beans for read only operations.

117.

How Do You Optimize Stateful Session Beans?

Answer»

• Tune Stateful SESSION beans CACHE size to avoid overhead of activation and passivation process.
• Set optimal Stateful session bean age(time-out) to avoid resource congestion.
USE 'transient' key word for unnecessary variables of Stateful session bean to avoid serialization overhead.
REMOVE Stateful session beans explicitly from client USING remove() method.

• Tune Stateful session beans cache size to avoid overhead of activation and passivation process.
• Set optimal Stateful session bean age(time-out) to avoid resource congestion.
• Use 'transient' key word for unnecessary variables of Stateful session bean to avoid serialization overhead.
• Remove Stateful session beans explicitly from client using remove() method.

118.

How Do You Optimize Stateless Session Beans?

Answer»

• Tune the Stateless SESSION beans POOL size to avoid OVERHEAD of creation and destruction of beans.
• Use setSessionContext() or ejbCreate() method to cache bean specific resources.
• Release ACQUIRED resources in ejbRemove() method.

• Tune the Stateless session beans pool size to avoid overhead of creation and destruction of beans.
• Use setSessionContext() or ejbCreate() method to cache bean specific resources.
• Release acquired resources in ejbRemove() method.

119.

What Are Common Optimizing Practices For Ejb?

Answer»

• Use Local interfaces that are available in EJB2.0 if you deploy both EJB Client and EJB in the same EJB Server.
• Use Vendor specific pass-by-reference implementation to make EJB1.1 remote EJBs as Local EJBs if you deploy both EJB Client and EJB in the same EJB Server.
• Wrap entity beans with session beans to reduce network calls and to promote declarative transactions. Optionally, make entity beans as local beans where appropriate.
• Make coarse grained session and entity beans to reduce network calls.
• Control serialization by modifying unnecessary data variables with 'transient' key WORD to avoid unnecessary data transfer over network.
CACHE EJBHome REFERENCES to avoid JNDI lookup overhead.
• Avoid transaction overhead for non-transactional methods of session beans by declaring 'NotSupported' or 'Never' transaction attributes that avoid further propagation of transactions.
• Set proper transaction age(time-out) to avoid large transaction.
• Use clustering for scalability.
• Tune thread count for EJB Server to increase EJB Server capacity.
• Choose servlet's HttpSession object rather than Stateful session bean to maintain client state if you don't require component architecture and services of Stateful session bean.
• Choose best EJB Server by testing with ECperf tool KIT.
• Choose normal java object over EJB if you don't want built-in services such as RMI/IIOP, transactions, security, persistence, resource pooling, thread SAFE, client state etc..

• Use Local interfaces that are available in EJB2.0 if you deploy both EJB Client and EJB in the same EJB Server.
• Use Vendor specific pass-by-reference implementation to make EJB1.1 remote EJBs as Local EJBs if you deploy both EJB Client and EJB in the same EJB Server.
• Wrap entity beans with session beans to reduce network calls and to promote declarative transactions. Optionally, make entity beans as local beans where appropriate.
• Make coarse grained session and entity beans to reduce network calls.
• Control serialization by modifying unnecessary data variables with 'transient' key word to avoid unnecessary data transfer over network.
• Cache EJBHome references to avoid JNDI lookup overhead.
• Avoid transaction overhead for non-transactional methods of session beans by declaring 'NotSupported' or 'Never' transaction attributes that avoid further propagation of transactions.
• Set proper transaction age(time-out) to avoid large transaction.
• Use clustering for scalability.
• Tune thread count for EJB Server to increase EJB Server capacity.
• Choose servlet's HttpSession object rather than Stateful session bean to maintain client state if you don't require component architecture and services of Stateful session bean.
• Choose best EJB Server by testing with ECperf tool kit.
• Choose normal java object over EJB if you don't want built-in services such as RMI/IIOP, transactions, security, persistence, resource pooling, thread safe, client state etc..

120.

How Do You Optimize A Jsp Page?

Answer»

• Use JSPINIT() method to cache static data
• Use StringBuffer rather than using + operator when you concatenate multiple strings
• Use print() method rather than println() method
• Use ServletOutputStream instead of JSPWriter to send binary data
• Initialize the 'out' object (implicit object) with proper size in the page directive.
• Flush the data partly.
• Minimize code in the synchronized block.
• Set the content length.
• Release resources in JSPDESTROY() method.
• Give 'false' value to the session in the page directive to avoid session object creation.
• Use include directive instead of include action when you want to include the child page content in the translation PHASE.
• Avoid giving unnecessary scope in the 'useBean' action.
• Do not use custom TAGS if you do not have reusability.
• Use application server caching facility.
• Use Mixed session mechanisms such as 'session' with hidden fields.
• Use 'session' and 'application' as cache.
• Use caching tags provided by different organizations like openSymphony.com.
• Remove 'session' objects explicitly in your program WHENEVER you finish the task.
• Reduce session time out value as much as possible.
• Use 'transient' variables to reduce serialization overhead if your session tracking mechanism uses serialization process.
• Disable JSP auto reloading feature.

• Use jspInit() method to cache static data
• Use StringBuffer rather than using + operator when you concatenate multiple strings
• Use print() method rather than println() method
• Use ServletOutputStream instead of JSPWriter to send binary data
• Initialize the 'out' object (implicit object) with proper size in the page directive.
• Flush the data partly.
• Minimize code in the synchronized block.
• Set the content length.
• Release resources in jspDestroy() method.
• Give 'false' value to the session in the page directive to avoid session object creation.
• Use include directive instead of include action when you want to include the child page content in the translation phase.
• Avoid giving unnecessary scope in the 'useBean' action.
• Do not use custom tags if you do not have reusability.
• Use application server caching facility.
• Use Mixed session mechanisms such as 'session' with hidden fields.
• Use 'session' and 'application' as cache.
• Use caching tags provided by different organizations like openSymphony.com.
• Remove 'session' objects explicitly in your program whenever you finish the task.
• Reduce session time out value as much as possible.
• Use 'transient' variables to reduce serialization overhead if your session tracking mechanism uses serialization process.
• Disable JSP auto reloading feature.

121.

How Do You Optimize Servlets?

Answer»

• Use init() method to cache static data.
• Use StringBuffer rather than using + OPERATOR when you concatenate multiple STRINGS.
• Use print() method rather than PRINTLN() method.
• Use ServletOutputStream rather than PrintWriter to send binary data.
• Initialize the PrintWriter with proper size.
• Flush the data partly.
• Minimize code in the SYNCHRONIZED block.
• Set the content length
• Release resources in destroy() method.
• Implement getLastModified() method to use browser cache and server cache
• Use application server caching facility
• Use Mixed session mechanisms such as HttpSession with hidden fields
• Remove HttpSession objects explicitly in your program whenever you finish the task.
• Reduce session time out value as much as possible.
• Use 'transient' variables to reduce serialization overhead if your HttpSession tracking mechanism uses serialization process.
• Disable servlet AUTO reloading feature.
• Use thread pool for your servlet engine and define the size as per application requirement.

• Use init() method to cache static data.
• Use StringBuffer rather than using + operator when you concatenate multiple strings.
• Use print() method rather than println() method.
• Use ServletOutputStream rather than PrintWriter to send binary data.
• Initialize the PrintWriter with proper size.
• Flush the data partly.
• Minimize code in the synchronized block.
• Set the content length
• Release resources in destroy() method.
• Implement getLastModified() method to use browser cache and server cache
• Use application server caching facility
• Use Mixed session mechanisms such as HttpSession with hidden fields
• Remove HttpSession objects explicitly in your program whenever you finish the task.
• Reduce session time out value as much as possible.
• Use 'transient' variables to reduce serialization overhead if your HttpSession tracking mechanism uses serialization process.
• Disable servlet auto reloading feature.
• Use thread pool for your servlet engine and define the size as per application requirement.

122.

How Will You Optimize Performance In Jdbc?

Answer»

• Use batch transactions.
• Choose right isolation level as per your requirement.
TRANSACTION_READ_UNCOMMITED gives best performance for concurrent transaction based applications. TRANSACTION_NONE gives best performance for non-concurrent transaction based applications.
• Use PreparedStatement when you execute the same statement more than once.
• Use CallableStatement when you want result from multiple and complex statements for a single REQUEST.
• Use batch update facility available in Statements.
• Use batch retrieval facility available in Statements or ResultSet.
• Set up proper direction for processing rows.
• Use proper getXXX() methods.
• Close ResultSet, Statement and Connection whenever you finish your work with them.
WRITE precise SQL queries.
• Cache read-only and read-mostly tables data.
FETCH small AMOUNT of data iteratively rather than whole data at once when retrieving large amount of data LIKE searching database etc.

• Use batch transactions.
• Choose right isolation level as per your requirement.
TRANSACTION_READ_UNCOMMITED gives best performance for concurrent transaction based applications. TRANSACTION_NONE gives best performance for non-concurrent transaction based applications.
• Use PreparedStatement when you execute the same statement more than once.
• Use CallableStatement when you want result from multiple and complex statements for a single request.
• Use batch update facility available in Statements.
• Use batch retrieval facility available in Statements or ResultSet.
• Set up proper direction for processing rows.
• Use proper getXXX() methods.
• Close ResultSet, Statement and Connection whenever you finish your work with them.
• Write precise SQL queries.
• Cache read-only and read-mostly tables data.
• Fetch small amount of data iteratively rather than whole data at once when retrieving large amount of data like searching database etc.

123.

How Do You Optimize Exceptions?

Answer»

• Be specific while handling the exception in your catch block.
• Be specific while THROWING exception in your throws clause.
• Do not use Exception Handling to control programming flow.
• Very little overhead is imposed by using exception handling MECHANISM unless an exception occurs or thrown a new exception object explicitly.
• Always use the finally block to release the resources to PREVENT resource LEAKS.
• Handle exceptions locally wherever POSSIBLE.
• Do not use Exception handling in loops.

• Be specific while handling the exception in your catch block.
• Be specific while throwing exception in your throws clause.
• Do not use Exception Handling to control programming flow.
• Very little overhead is imposed by using exception handling mechanism unless an exception occurs or thrown a new exception object explicitly.
• Always use the finally block to release the resources to prevent resource leaks.
• Handle exceptions locally wherever possible.
• Do not use Exception handling in loops.

124.

How Do You Optimize Io?

Answer»

• Use Buffered IO classes.
• File information such as file length requires a system call and can be slow. Don't use it often. Similarly, System.currentTimeMillis() USES a native call to get current time. Make sure your production code does not have this statement.
• Many java.io.File methods are system calls which can be slow.
• Use BufferedIO streams to ACCESS URLConnection sInput/Output streams.
• Use the transient keyword to define fields to avoid having those fields SERIALIZED. Examine serialized objects to DETERMINE which fields do not NEED to be serialized for the application to work.
• Increase server listen queues for high load or high latency servers.

• Use Buffered IO classes.
• File information such as file length requires a system call and can be slow. Don't use it often. Similarly, System.currentTimeMillis() uses a native call to get current time. Make sure your production code does not have this statement.
• Many java.io.File methods are system calls which can be slow.
• Use BufferedIO streams to access URLConnection sInput/Output streams.
• Use the transient keyword to define fields to avoid having those fields serialized. Examine serialized objects to determine which fields do not need to be serialized for the application to work.
• Increase server listen queues for high load or high latency servers.

125.

How Do You Optimize Threads?

Answer»

• Avoid synchronization where possible
• Code a multi-thread for multi-processor machine.
• Synchronizing on method rather than code blocks is SLIGHTLY FASTER.
• Polling is only acceptable when waiting for outside events and should be performed in a "side" thread. Use wait/NOTIFY instead.
• Prioritize threads. Use notify instead of notifyAll. Use synchronization sparingly.
KEEP synchronized methods out of loops if you possibly can.
• Maximize thread lifetimes and minimize thread creation/destruction cycles.
• Use Thread pools where these improve performance.
• Use Thread.sleep() instead of a for loop for measured delays.
• Use a separate timer thread to timeout socket operations.
• Use more server threads if multiple connections have HIGH latency.

• Avoid synchronization where possible
• Code a multi-thread for multi-processor machine.
• Synchronizing on method rather than code blocks is slightly faster.
• Polling is only acceptable when waiting for outside events and should be performed in a "side" thread. Use wait/notify instead.
• Prioritize threads. Use notify instead of notifyAll. Use synchronization sparingly.
• Keep synchronized methods out of loops if you possibly can.
• Maximize thread lifetimes and minimize thread creation/destruction cycles.
• Use Thread pools where these improve performance.
• Use Thread.sleep() instead of a for loop for measured delays.
• Use a separate timer thread to timeout socket operations.
• Use more server threads if multiple connections have high latency.

126.

How Do You Optimize Arrays, Vectors And Collections?

Answer»

• Create copies of simple array by initializing them through loops or by using System.arraycopy(), create copies of COMPLEX arrays by cloning them.
• Iterator.hasNext() and Enumerator.hasMoreElements() need not be repeatedly called when the size of the collection is known. Use collection.size() and a loop counter instead.
• ArrayList is faster than Vector
• Go for a non-synchronized version of collection unless used in a threaded application
• LinkedList is faster than ArrayList for inserting elements to the front of the array, but slower at indexed lookup.
• Accessing arrays is much faster than accessing vectors, String, and StringBuffer
• Vector is convenient to use, but inefficient. Ensure that elementAt() is not used inside a loop.
• Re-use Hashtables by using Hashtable.clear().
• Removing elements from a Vector will necessitate copying within the Vector if the element is removed from anywhere other than the end of the collection.
• Presizing collections to the expected size is more efficient than using the default size and letting the collection GROW.
• For multidimensional arrays store a reference for the currently accessed row in a variable.
• When ADDING MULTIPLE items to a collection, add them all in one CALL if possible.

• Create copies of simple array by initializing them through loops or by using System.arraycopy(), create copies of complex arrays by cloning them.
• Iterator.hasNext() and Enumerator.hasMoreElements() need not be repeatedly called when the size of the collection is known. Use collection.size() and a loop counter instead.
• ArrayList is faster than Vector
• Go for a non-synchronized version of collection unless used in a threaded application
• LinkedList is faster than ArrayList for inserting elements to the front of the array, but slower at indexed lookup.
• Accessing arrays is much faster than accessing vectors, String, and StringBuffer
• Vector is convenient to use, but inefficient. Ensure that elementAt() is not used inside a loop.
• Re-use Hashtables by using Hashtable.clear().
• Removing elements from a Vector will necessitate copying within the Vector if the element is removed from anywhere other than the end of the collection.
• Presizing collections to the expected size is more efficient than using the default size and letting the collection grow.
• For multidimensional arrays store a reference for the currently accessed row in a variable.
• When adding multiple items to a collection, add them all in one call if possible.

127.

How Do You Optimize Strings?

Answer»

• Use StringBuffer instead of STRING concat '+' operator
• Formatting NUMBERS using java.text.DecimalFormat is ALWAYS SLOWER than Double.toString(double) method, because internally java.text.DecimalFormat() CALLS Double.toString(double) then parses and converts the results.
• Convert String to char[] arrays to process characters rather than accessing one at a time using String.charAt() method
• Creating Double from string is slow
• Intern() Strings to enable (==) comparisions
• Use char arrays for all character processing in loops, rather than using String or StringBuffer classes
• Set the initial string buffer size to maximum if it known.
• StringTokenizer is very inefficient, and can be optimized by storing the string and delimiter in a character array instead of in String.
• DON'T create static strings via new().
• Where the compiler cannot resolve concatenated strings at compile time, the code should be converted to StringBuffer appends, and the StringBuffer should be appropriately sized rather than using the default size.
• The compiler concatenates strings where they are fully resolvable, so don t move these concatenations to runtime with StringBuffer.

• Use StringBuffer instead of String concat '+' operator
• Formatting numbers using java.text.DecimalFormat is always slower than Double.toString(double) method, because internally java.text.DecimalFormat() calls Double.toString(double) then parses and converts the results.
• Convert String to char[] arrays to process characters rather than accessing one at a time using String.charAt() method
• Creating Double from string is slow
• Intern() Strings to enable (==) comparisions
• Use char arrays for all character processing in loops, rather than using String or StringBuffer classes
• Set the initial string buffer size to maximum if it known.
• StringTokenizer is very inefficient, and can be optimized by storing the string and delimiter in a character array instead of in String.
• DON'T create static strings via new().
• Where the compiler cannot resolve concatenated strings at compile time, the code should be converted to StringBuffer appends, and the StringBuffer should be appropriately sized rather than using the default size.
• The compiler concatenates strings where they are fully resolvable, so don t move these concatenations to runtime with StringBuffer.

128.

How Do You Optimize Loops And Conditional Statements?

Answer»

• Reduce the number of temporary objects being used,especially in loops.
• Use short-circuit Boolean operators INSTEAD of normal Boolean operators.
• Eliminate unnecessary repeated method calls from loops.
• Move loop invariants outside the loop.
• Perform the loop BACKWARDS (this actually performs SLIGHTLY faster than FORWARD loops do). [Actually it is converting the test to compare against 0 that makes the difference].
• It can help to copy slower-access vars to fast local vars if you are going to operate on them repeatedly, as in a loop.
• Use exception TERMINATED infinite loops for long loops.
• Whatever can be calculated outside of a loop should be calculated outside of the loop.
• For multidimensional arrays store a reference for the currently accessed row in a variable.
• Cache the size of the collection in a local variable to use in a loop instead of repeatedly calling collection.size().

• Reduce the number of temporary objects being used,especially in loops.
• Use short-circuit Boolean operators instead of normal Boolean operators.
• Eliminate unnecessary repeated method calls from loops.
• Move loop invariants outside the loop.
• Perform the loop backwards (this actually performs slightly faster than forward loops do). [Actually it is converting the test to compare against 0 that makes the difference].
• It can help to copy slower-access vars to fast local vars if you are going to operate on them repeatedly, as in a loop.
• Use exception terminated infinite loops for long loops.
• Whatever can be calculated outside of a loop should be calculated outside of the loop.
• For multidimensional arrays store a reference for the currently accessed row in a variable.
• Cache the size of the collection in a local variable to use in a loop instead of repeatedly calling collection.size().

129.

How Do You Optimize Methods In A Class?

Answer»

• Avoid creating temporary objects WITHIN frequently called methods.
• Define methods that accept reusable objects to be filled in with data, rather than methods that return objects holding that data.
• Use methods that alter objects without MAKING copies.
• Eliminate repeatedly called methods where alternatives are possible [For example, if you are processing a vector in a loop, get the size of the vector in the BEGINNING in a length local variable rather than calling size() method on the vector in the condition part of the for loop]
• Use private and STATIC methods and final classes to encourage inlining by the compiler.
• Inline methods manually where it is appropriate • KEEP methods short and simple to make them automatic inlining candidates.
• Access to private member by the inner classes to the enclosing class goes by a method call even if it is not intended to.
• Keep synchronized methods out of loops if you possibly can.

• Avoid creating temporary objects within frequently called methods.
• Define methods that accept reusable objects to be filled in with data, rather than methods that return objects holding that data.
• Use methods that alter objects without making copies.
• Eliminate repeatedly called methods where alternatives are possible [For example, if you are processing a vector in a loop, get the size of the vector in the beginning in a length local variable rather than calling size() method on the vector in the condition part of the for loop]
• Use private and static methods and final classes to encourage inlining by the compiler.
• Inline methods manually where it is appropriate • Keep methods short and simple to make them automatic inlining candidates.
• Access to private member by the inner classes to the enclosing class goes by a method call even if it is not intended to.
• Keep synchronized methods out of loops if you possibly can.

130.

H:inputsecret Field Becomes Empty When Page Is Reloaded. How To Fix This?

Answer»

SET redisplay=true, it is FALSE by DEFAULT.

Set redisplay=true, it is false by default.

131.

Is It Possible To Have More Than One Faces Configuration File?

Answer»

Yes. You can define the list of the configuration FILES in the web.xml.
This is an example:

<context- param> <param- NAME> javax .FACES.CONFIG_ FILES </param- name> <param-value> /WEB-INF /faces- config- NAVIGATION .xml, /WEB- INF /faces- BEANS .xml </param- value></context-param>

Yes. You can define the list of the configuration files in the web.xml.
This is an example:

<context- param> <param- name> javax .faces.CONFIG_ FILES </param- name> <param-value> /WEB-INF /faces- config- navigation .xml, /WEB- INF /faces- beans .xml </param- value></context-param>

132.

What Is The Different Between Getrequestparametermap() And Getrequestparametervaluesmap()

Answer»

getRequestParameterValuesMap() SIMILAR to getRequestParameterMap(), but contains MULTIPLE VALUES for for the parameters with the same name. It is important if you one of the components such as &LT;h:selectMany>.

getRequestParameterValuesMap() similar to getRequestParameterMap(), but contains multiple values for for the parameters with the same name. It is important if you one of the components such as <h:selectMany>.

133.

How To Show Confirmation Dialog When User Click The Command Link?

Answer»

h:commandLink assign the ONCLICK attribute for internal use. So, you cannot use it to write your own code. This problem will fixed in the JSF 1.2. For the current JSF version you can use onmousedown event that OCCURS before onclick. <script LANGUAGE="javascript"> function ConfirmDelete(link) { VAR delete = CONFIRM('Do you want to Delete?'); if (delete == true) { link.onclick(); } } </script> . . . . <h:commandLink action="delete" onmousedown="return ConfirmDelete(this);"> <h:outputText value="delete it"/> </h:commandLink>

h:commandLink assign the onclick attribute for internal use. So, you cannot use it to write your own code. This problem will fixed in the JSF 1.2. For the current JSF version you can use onmousedown event that occurs before onclick. <script language="javascript"> function ConfirmDelete(link) { var delete = confirm('Do you want to Delete?'); if (delete == true) { link.onclick(); } } </script> . . . . <h:commandLink action="delete" onmousedown="return ConfirmDelete(this);"> <h:outputText value="delete it"/> </h:commandLink>

134.

How To Reload The Page After Valuechangelistener Is Invoked?

Answer»

At the END of the VALUECHANGELISTENER, CALL FacesContext.getCurrentInstance().renderResponse()

At the end of the ValueChangeListener, call FacesContext.getCurrentInstance().renderResponse()

135.

How To Access Web.xml Init Parameters From Java Code?

Answer»

You can get it USING externalContext getInitParameter METHOD. For example, if you have:
connectionString JDBC:oracle:thin:scott/tiger@cartman:1521:O901DB
You can access this CONNECTION STRING with:
FacesContext fc = FacesContext.getCurrentInstance();
String connection = fc.getExternalContext().getInitParameter("connectionString");

You can get it using externalContext getInitParameter method. For example, if you have:
connectionString jdbc:oracle:thin:scott/tiger@cartman:1521:O901DB
You can access this connection string with:
FacesContext fc = FacesContext.getCurrentInstance();
String connection = fc.getExternalContext().getInitParameter("connectionString");

136.

How To Get Current Page Url From Backing Bean?

Answer»

You can get a reference to the HTTP request object via FacesContext like this:

FacesContext fc = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();

And then use the NORMAL request METHODS to OBTAIN path information. Alternatively,
context.getViewRoot().getViewId();
will RETURN you the name of the current JSP (JSF view IDS are basically just JSP path names).

You can get a reference to the HTTP request object via FacesContext like this:

FacesContext fc = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();

And then use the normal request methods to obtain path information. Alternatively,
context.getViewRoot().getViewId();
will return you the name of the current JSP (JSF view IDs are basically just JSP path names).

137.

How To Add Context Path To Url For Outputlink?

Answer»

Current JSF implementation does not ADD the CONTEXT path for OUTPUTLINK if the defined path STARTS with '/'. To correct this problem use #{facesContext.externalContext.requestContextPath} prefix at the beginning of the outputLink value attribute. For example: 
&LT;h:outputLink value="#{facesContext.externalContext.requestContextPath}/myPage.faces">

Current JSF implementation does not add the context path for outputLink if the defined path starts with '/'. To correct this problem use #{facesContext.externalContext.requestContextPath} prefix at the beginning of the outputLink value attribute. For example: 
<h:outputLink value="#{facesContext.externalContext.requestContextPath}/myPage.faces">

138.

What Is Javaserver Faces?

Answer»

JavaServer Faces (JSF) is a user interface (UI) FRAMEWORK for Java web applications. It is designed to significantly ease the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a target client. JSF provides ease-of-use in the following ways: Makes it easy to construct a UI from a set of reusable UI components Simplifies migration of application DATA to and from the UI Helps manage UI state across server requests Provides a simple model for wiring client-generated events to server-side application code Allows custom UI components to be easily built and re-used .

Most IMPORTANTLY, JSF establishes standards which are designed to be leveraged by tools to provide a developer experience which is accessible to a wide variety of developer types, ranging from corporate developers to systems programmers. A "corporate developer" is characterized as an individual who is proficient in writing procedural code and business logic, but is not necessarily skilled in object-oriented PROGRAMMING. A "systems programmer" understands object-oriented fundamentals, including abstraction and DESIGNING for re-use. A corporate developer typically relies on tools for development, while a system programmer may define his or her tool as a text editor for writing code. Therefore, JSF is designed to be tooled, but also exposes the framework and programming model as APIs so that it can be used outside of tools, as is sometimes required by systems programmers.

JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications. It is designed to significantly ease the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a target client. JSF provides ease-of-use in the following ways: Makes it easy to construct a UI from a set of reusable UI components Simplifies migration of application data to and from the UI Helps manage UI state across server requests Provides a simple model for wiring client-generated events to server-side application code Allows custom UI components to be easily built and re-used .

Most importantly, JSF establishes standards which are designed to be leveraged by tools to provide a developer experience which is accessible to a wide variety of developer types, ranging from corporate developers to systems programmers. A "corporate developer" is characterized as an individual who is proficient in writing procedural code and business logic, but is not necessarily skilled in object-oriented programming. A "systems programmer" understands object-oriented fundamentals, including abstraction and designing for re-use. A corporate developer typically relies on tools for development, while a system programmer may define his or her tool as a text editor for writing code. Therefore, JSF is designed to be tooled, but also exposes the framework and programming model as APIs so that it can be used outside of tools, as is sometimes required by systems programmers.

139.

What Is The Difference Between Point To Point And Publish/subscribe Messaging Domains?

Answer»

A point-to-point (PTP) product or application is built around the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from the queue(s) established to hold their messages. Queues retain all messages sent to them until the messages are consumed or until the messages expire.

In a publish/subscribe (pub/sub) product or application, clients ADDRESS messages to a topic. Publishers and SUBSCRIBERS are generally anonymous and may dynamically publish or subscribe to the content HIERARCHY. The system takes CARE of distributing the messages arriving from a topic's multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers.

A point-to-point (PTP) product or application is built around the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from the queue(s) established to hold their messages. Queues retain all messages sent to them until the messages are consumed or until the messages expire.

In a publish/subscribe (pub/sub) product or application, clients address messages to a topic. Publishers and subscribers are generally anonymous and may dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a topic's multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers.

140.

What Is The Diffrence Between Java Mail And Jms Queue?

Answer»

Java Mail - API siting on TOP of e-mail protocols like SMTP, POP, IMAP - essentially same STUFF e-mail clients like MS outlook use .. hence make sense if at least on one SIDE of conversation we have human. 

JMS Queue - is asynchronous point-to-point communication between SYSTEMS 

Java Mail - API siting on top of e-mail protocols like SMTP, POP, IMAP - essentially same stuff e-mail clients like MS outlook use .. hence make sense if at least on one side of conversation we have human. 

JMS Queue - is asynchronous point-to-point communication between systems 

141.

What Is The Difference Between Ic And Queue?

Answer»

A ic is TYPICALLY USED for ONE to MANY messaging i.e. it supports publish subscribe model of messaging. While queue is used for one-to-one messaging i.e. it supports Point to Point Messaging.

A ic is typically used for one to many messaging i.e. it supports publish subscribe model of messaging. While queue is used for one-to-one messaging i.e. it supports Point to Point Messaging.

142.

What Are The Three Components Of A Message ?

Answer»

A JMS message consists of three parts:

Message header 
For message identification. For example, the header is used to determine if a GIVEN message is appropriate for a "SUBSCRIBER

Properties 
For application-specific, provider-specific, and optional header fields 

Body 
Holds the content of the message. SEVERAL formats are supported, including TextMessage, which wrap a simple String, that wrap arbitrary Java objects (which MUST be serializable). Other formats are supported as WELL

A JMS message consists of three parts:

Message header 
For message identification. For example, the header is used to determine if a given message is appropriate for a "subscriber" 

Properties 
For application-specific, provider-specific, and optional header fields 

Body 
Holds the content of the message. Several formats are supported, including TextMessage, which wrap a simple String, that wrap arbitrary Java objects (which must be serializable). Other formats are supported as well. 

143.

What Kind Of Information Found In The Header Of A Message ?

Answer»

The header of a MESSAGE contains message identification and ROUTING information. This INCLUDES , but is not limited to :

JMSDestination
JMSDeliveryMode
JMSMessageID
JMSTimeStamp
JMSExpiration
JMSReplyTO
JMSCorrelationID
JMSType
JMSRedelivered 

The header of a message contains message identification and routing information. This includes , but is not limited to :

JMSDestination
JMSDeliveryMode
JMSMessageID
JMSTimeStamp
JMSExpiration
JMSReplyTO
JMSCorrelationID
JMSType
JMSRedelivered 

144.

What Is The Difference Between Bytesmessage And Streammessage?

Answer»

BytesMessage stores the primitive data types by converting them to their BYTE representation. Thus the message is one CONTIGUOUS stream of bytes. While the StreamMessage maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. BytesMessage allows data to be read using any type. Thus EVEN if your payload contains a LONG value, you can invoke a METHOD to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the StreamMessage. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read.

BytesMessage stores the primitive data types by converting them to their byte representation. Thus the message is one contiguous stream of bytes. While the StreamMessage maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. BytesMessage allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the StreamMessage. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read.

145.

Why Doesn't The Jms Api Provide End-to-end Synchronous Message Delivery And Notification Of Delivery?

Answer»

Some messaging systems provide synchronous delivery to destinations as a MECHANISM for implementing RELIABLE applications. Some systems provide clients with various forms of delivery NOTIFICATION so that the clients can detect dropped or ignored messages. This is not the model defined by the JMS API.

JMS API messaging provides guaranteed delivery via the once-and-only-once delivery semantics of PERSISTENT messages. In ADDITION, MESSAGE consumers can ensure reliable processing of messages by using either CLIENT_ACKNOWLEDGE mode or transacted sessions. This achieves reliable delivery with minimum synchronization and is the enterprise messaging model most vendors and developers prefer.

The JMS API does not define a schema of systems messages (such as delivery notifications). If an application requires acknowledgment of message receipt, it can define an application-level acknowledgment message.

Some messaging systems provide synchronous delivery to destinations as a mechanism for implementing reliable applications. Some systems provide clients with various forms of delivery notification so that the clients can detect dropped or ignored messages. This is not the model defined by the JMS API.

JMS API messaging provides guaranteed delivery via the once-and-only-once delivery semantics of PERSISTENT messages. In addition, message consumers can ensure reliable processing of messages by using either CLIENT_ACKNOWLEDGE mode or transacted sessions. This achieves reliable delivery with minimum synchronization and is the enterprise messaging model most vendors and developers prefer.

The JMS API does not define a schema of systems messages (such as delivery notifications). If an application requires acknowledgment of message receipt, it can define an application-level acknowledgment message.

146.

What Are The Various Message Types Supported By Jms?

Answer»

Stream MESSAGES -- Group of Java Primitives
Map Messages -- NAME Value Pairs. Name being a string&AMP; Value being a java primitive
Text Messages -- String messages (SINCE being widely used a separate MESSAGING Type has been supported)
Object Messages -- Group of serialize able java object
Bytes Message -- Stream of uninterrupted bytes.

Stream Messages -- Group of Java Primitives
Map Messages -- Name Value Pairs. Name being a string& Value being a java primitive
Text Messages -- String messages (since being widely used a separate messaging Type has been supported)
Object Messages -- Group of serialize able java object
Bytes Message -- Stream of uninterrupted bytes.

147.

What Is A Good Directory Structure For Main Code And Junit Test Code?

Answer»

DEV
|_src
| |_com
| |_mycom
| |_mypkg
| |_A.java
|_test
|_src
|_com
|_mycom
|_mypkg
|_ATest.java

Dev
|_src
| |_com
| |_mycom
| |_mypkg
| |_A.java
|_test
|_src
|_com
|_mycom
|_mypkg
|_ATest.java

148.

How To Let Auto-detect Platform And Use Platform Specific Properties?

Answer»

Tell you a GREAT trick, it WORKS excellent.
In your major build-include.xml, put in this line

<property file="${antutil.includes}/${os.name}-${os.arch}.properties" />

This will auto-detect your PLATFORM, and you write ONE file for each environment specific variables. For example: HP-UX-PA_RISC2.0.properties SunOS-sparc.properties Windows XP-x86.properties ... They work great!!! 

Tell you a great trick, it works excellent.
In your major build-include.xml, put in this line

<property file="${antutil.includes}/${os.name}-${os.arch}.properties" />

This will auto-detect your platform, and you write one file for each environment specific variables. For example: HP-UX-PA_RISC2.0.properties SunOS-sparc.properties Windows XP-x86.properties ... They work great!!! 

149.

Can I Change/override Ant Properties When I Use Ant-contrib Foreach Task?

Answer»

<FOREACH> is actually USING a DIFFERENT property space, you can pass any property name/value pair to it. Just use <PARAM> nested tag INSIDE foreach

<foreach> is actually using a different property space, you can pass any property name/value pair to it. Just use <param> nested tag inside foreach

150.

How To Do Conditional Statement In Ant?

Answer»

There are many ways to solve the problem.

  • Since target if/unless all depend on some property is defined or not, you can USE CONDITION to define different NEW PROPERTIES, which in turn depends on your ant property values. This makes your ant script very flexible, but a little hard to read.
  • Ant-contrib has <if> <switch> tasks for you to use.
  • Ant-contrib ALSO has <propertyregex> which can make very complicate decisions. 

 

There are many ways to solve the problem.