Popular Posts

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, March 19, 2012

Detecting and fixing memory leaks in java

What sort of memory leaks are possible in Java and how do I prevent them?

In any language, application-level memory management problems revolve around the deallocation of memory. These problems fall into two categories: premature deallocation (corrupted pointers) and incomplete deallocation (memory leaks).
In the case of incomplete deallocation, there are two subcases: coding bugs and design bugs. Coding bugs are language dependent. In the case of C, this would involve free()ing less than was malloc()ed, while in C++ this might involve using delete in lieu of delete[]. Design bugs, on the other hand, do not depend on the language; instead, they involve simple programmer negligence.
In languages like C/C++, all memory management is handled by the programmer, so all of these problems can arise, even after the programmer has expended much effort to ensure the code is free of such defects. In fact, in C/C++ the more you try to avoid memory leaks, the more likely you are to create corrupted pointers, and vice versa. And, by nature the risk of such bugs increases with code size and complexity, so it's difficult to protect large C/C++ applications from these types of bugs.
In Java, on the other hand, the Java language and runtime together entirely eliminate the problems of corrupted pointers and code-level memory leaks. Here's how:
  • In Java, memory is allocated only to objects. There is no explicit allocation of memory, there is only the creation of new objects. (Java even treats array types as objects.)
  • The Java runtime employs a garbage collector that reclaims the memory occupied by an object once it determines that object is no longer accessible. This automatic process makes it safe to throw away unneeded object references because the garbage collector does not collect the object if it is still needed elsewhere. Therefore, in Java the act of letting go of unneeded references never runs the risk of deallocating memory prematurely.
  • In Java, it's easy to let go of an entire "tree" of objects by setting the reference to the tree's root to null; the garbage collector will then reclaim all the objects (unless some of the objects are needed elsewhere). This is a lot easier than coding each of the objects' destructors to let go of its own dependencies (which is a coding-level problem with C++).


So what about memory leaks caused by poor program design? In such designs, unnecessary object references originating in long-lived parts of the system prevent the garbage collector from reclaiming objects that are in fact no longer needed. Such errors typically involve a failure "in the large" to properly encapsulate object references among various parts of the code.
Another design flaw occurs "in the small," at the level of a faulty algorithm; the use of Collections objects in such cases will typically magnify the error.
As the technology improves, a suitably implemented JVM could help reduce the effects of such designed-in memory leaks by using the garbage collector to track object usage over time. The garbage collector could then rearrange objects in memory according to a freshness factor based on when they were last referenced, for example. Stale objects would become eligible for physical RAM swap-out (even though, for safety, they would still exist).
Ideally of course, programmers would design applications with objects' lifecycles in mind, rather than rely on clever features of state-of-the-art JVM implementations.
In conclusion: Design problems can be mitigated by letting go of object references in one's own classes as soon as one can (knowing that in Java there is no risk of damaging another part of the code).
Tip: The KL Group's JProbe tool can help identify possible sources of memory leaks by showing which objects are holding on to graphs of references to other objects.
Note: Implementations of Sun's JVM prior to HotSpot used a technique called conservative garbage collection, which could introduce memory leaks of its own, beyond those caused by the programmer. To wit, as long as the application contained a 32-bit integer primitive (int) whose value coincided with the address of an object, the garbage collector would not reclaim the object. Although the likelihood was small, it wasn't zero. For this reason, and for the best performance in general, use HotSpot where possible.



Refer :

Sunday, March 11, 2012

Immutable objects in java

An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. In some cases, an object is considered immutable even if some internally used attributes change but the object's state appears to be unchanging from an external point of view. For example, an object that uses memoization to cache the results of expensive computations could still be considered an immutable object.
               Immutable objects are often useful because they are inherently thread-safe. Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.Small immutable objects can easily be copied efficiently, but larger immutable objects require more complicated persistent data structure algorithms to be efficiently copied. Mutable objects are sometimes used instead of immutable objects for performance reasons.

Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

Programmers are often reluctant to employ immutable objects, because they worry about the cost of creating a new object as opposed to updating an object in place. The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.
Check here for how immutable objects are thread safe ?

Refer : http://www.javaranch.com/journal/2003/04/immutable.htm
http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html

Scalable web application


What is scalable application design : 
Tip 1: load balancing the webserver
Tip 2: scaling from a single DB server to a Master-Slave setup
Tip 3: Partitioning, Vertical DB Scaling
Tip 4: Partitioning, horizontal DB Scaling
Tip 5: Application Level Partitioning
Tip 6: Caching to get around your database

Refer : http://blog.nickbelhomme.com/php/scalable-web-applications_158

Also refer :
http://www.infoq.com/news/2010/08/Scalable-Web-Application

Object oriented design questions

Design does not mean implementation.
Design means:
  1. what all classes you will have
  2. The methods(functionality) your classes will provide
  3. What will be the relation between classes you have
  4. What will be the Lifetimes of objects of your classed
  5. Having said a design is not something which gets done in a mere 15-20mins of an interview.It's all blood and sweat and it needs lot of time and consideration albeit discussions to arrive at a good design.
  6. In a interview the Questioner usually want to know if you can think in the right direction atleast.
Check design pattern interview questions here

Interview questions : 

Frequently Used java APIs'


Important java API’s to remember  :
·         Comparable
·         Comparator
·         List
·         LinkedList
·         ArrayList
·         Vector
·         Set
·         HashSet
·         TreeSet
·         SortedSet
·         Map
·         TreeMap
·         HashMap
·         SortedMap
·         Serializable
·         Clonable
·         Integer,Double,Boolean,Long
·         String
·         Object
·         Thread
·         Runnable interface
·         HttpServlet
·         HttpSession
·         Collections
·         Arrays
·         Generics
·         Java.lang.Math
·         StringBuffer
·         StringBuilder
·         ThreadLocal
·         Iterator
·         Enumerator
·         Date
·         Calendar
·         LinkedHashSet
·         LinkedHashMap
·         PriorityQueue
·         Random
·         Stack<E>
·         WeakHashMap
·         Pattern
·         Matcher

Thursday, March 8, 2012

Memcached

From POSIX to COM/DCOM or RMI to SOAP, we simply try to share data among threads or applications. By decoupling service with client, Memcached is a new and better solution to share data. Because Memcached is an abstract service, it can serve different applications written in different programming languages running on different platforms simultaneously.

Memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load. In short, Memcached is a huge hashmap.
public class DummyServiceImpl {

//CustomMemCachedClient is wrapper class internally developed in our product to access cache
private CustomMemCachedClient mCustomMemCachedClient;
public String retrieveDummy(String regId) {
String dummy = null;
String key = "dummy#" + regId;
Object cachedValue = mCustomMemCachedClient.get(key);

if (cachedValue instanceof String) {
dummy = (String)cachedValue;
}
if (dummy == null) {
dummy = "dummy has been set for regId: " + regId;
System.out.println("dummy is just set for " + regId);
mCustomMemCachedClient.set(key, dummy);
}

return dummy;
}

public CustomMemCachedClient getCustomMemCachedClient() {
return mCustomMemCachedClient;
}
public void setCustomMemCachedClient(
CustomMemCachedClient pCustomMemCachedClient) {
mCustomMemCachedClient = pCustomMemCachedClient;
}

}

Now, let's study the results of the tests above. When user A login, there was no dummy data in memcached. So, the dummy service generated dummy data and stored it in memcached under key "dummy#A". When user A refresh the page, dummy service was able to grep data right out of memcached, so no new dummy data was generated. Since we set timer as 10 seconds for dummy data to stale, new dummy data need to be generated after a timeout. From these, we can see how memcached caches data. But does it work the same way as hard coding? When user B login, there was no dummy data for that user in memcached yet. All memcached had was for user A, so dummy service generated a new dummy data for user B under key "dummy#B". From there, user B should have the same experience as user A had.
MemCached is just that simple. 

In web applications the majority of the latency in serving a request is caused by interactions with a database. Databases are often necessary for managing persistence and to providing a way to sort and filter large collections of information. However, databases are also overused to frequently read and write infrequently-changed information -- or worse, information that never changes.Memcached provides a shared memory cache where arbitrary information can be read frequently without incurring the overhead of a database.

Refer : http://wiki.cerb4.com/wiki/Performance#Memcached

Wednesday, March 7, 2012

Design patterns

J unit test

Types of testing :
  • Unit testing : The goal of unit testing is to test each part of the program in isolation and show that the individual parts are correct, and identify programming/logical issues at a low level, thereby promoting an Extreme Programming paradigm.
         Unit testing is engraved into Extreme Programming methodology, and hence strive to make it cost effective.
Perform white box testing of each line of code. Testing should be narrow, covering each line of code.
  • Integration testing
  • End to end testing(QA)
  • Performance testing
  • Smoke testing
White Box Test : 
    Requires the knowledge of implementation
    Requires program language, script like HTMLUNIT, Selenium in Java
    Since the tests are based on the actual implementation, if the implementation changes, the tests probably will need to change, too.
Black Box Test :
    Requires NO knowledge of implementation
    No programing but use tool like STIQ
    Try to explore the software's behavior from the outside

Refer here for Junit frame work

Optimistic locking failure

There are cases like multiple threads try to modify the entries depending on the already existing row information.If one thread commits the
info after other thread reads the info,then date will get corrupted and will lead to abnormal behavior.To avoid this condition,we add one more column in database tables
so thatwhen a thread reads the row,it will increase this value in column to one and before writing the info it will recheck.If both are same,then commits the value.Otherwise
it will throw optimistic lodking failure exception.


Optimistic Locking is a strategy where you read a record, take note of a version number and check that the version hasn't changed before you write the record back. When you write the record back you filter the update on the version to make sure it's atomic. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit.
If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it.
This strategy is most applicable to high-volume systems and three-tier architectures where you do not necessarily maintain a connection to the database for your session. In this situation the client cannot actually maintain database locks as the connections are taken from a pool and you may not be using the same connection from one access to the next.
Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoidDeadlocks. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a two tier client server application) or an externally available transaction ID that can be used independently of the connection.
In the latter case you open the transaction with the TxID and then reconnect using that ID. The DBMS maintains the locks and allows you to pick the session back up through the TxID. This is how distributed transactiona using two-phase commit protocols (such as XA or COM+ Transactions) work.

Spring framework

What is Spring

Spring is a lightweight inversion of control and aspect-oriented container framework.
Explain Spring

      Lightweight : Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.
    Inversion of control (IoC) : Loose coupling is achieved in springusing the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.
    Aspect oriented (AOP) : Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services.
    Container : Spring contains and manages the life cycle and configuration of application objects.
    Framework : Spring provides most of the intra functionality leaving rest of the coding to the developer.

What are the different modules in Spring framework

    The Core container module
    Application context module
    AOP module (Aspect Oriented Programming)
    JDBC abstraction and DAO module
    O/R mapping integration module (Object/Relational)
    Web module
    MVC framework module

What is the Core container module

This module is provides the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework was built on the top of this module. This module makes the Spring container.
What is Application context module

The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.
What is AOP module

The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata programming to Spring. Using Spring’s metadata support, we will be able to add annotations to our source code that instruct Spring on where and how to apply aspects.
What is JDBC abstraction and DAO module

Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought in this module. In addition, this module uses Spring’s AOP module to provide transaction management services for objects in a Spring application.
What are object/relational mapping integration module

Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.
What is web module

This module is built on the application context module, providing a context that is appropriate for web-based applications. This module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and programmatic binding of request parameters to yourbusiness objects. It also contains integration support with Jakarta Struts.

Refer : http://en.wikipedia.org/wiki/Spring_Framework

Thread pool

Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks.

Using worker threads minimizes the overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and deallocating many thread objects creates a significant memory management overhead.

One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Tasks are submitted to the pool via an internal queue, which holds extra tasks whenever there are more active tasks than threads.

An important advantage of the fixed thread pool is that applications using it degrade gracefully. To understand this, consider a web server application where each HTTP request is handled by a separate thread. If the application simply creates a new thread for every new HTTP request, and the system receives more requests than it can handle immediately, the application will suddenly stop responding to all requests when the overhead of all those threads exceed the capacity of the system. With a limit on the number of the threads that can be created, the application will not be servicing HTTP requests as quickly as they come in, but it will be servicing them as quickly as the system can sustain.

Thread pool pattern : http://en.wikipedia.org/wiki/Thread_pool_pattern

Tuesday, March 6, 2012

Java frequent interview questions

=====================================================================
Java interview questions : 
5) What is hashcode and equals contract?
6) What is the difference between == and equals method?
8) What is the difference between String and StringBuffer classes?
9) What is the way to store the integer value in a string object to an integer variable?
10) What are sorted collections in Java?
12) What is JDBC API?
14) What is final, finally and finalize?
15)********** What is weakhashmap?
16) ************What is the purpose of reflection API?
18) What is bucketing in Java?
19)*************** How does Java manages the threads?
23) **************What are the different ways of creating a thread?
24) ************** What is inter thread communication?
25) ************** What are instance and class level locks? What is synchronization?
29) What are the coding standards for naming variables, constants, methods and classes?
30) What is a literal and what is special about String literals?
31) **************What is flyweight design pattern?
32) **************How will you create a Singleton class? Is it thread safe?
35) What is the purpose of instanceof operator?
37) What is the difference between private, protected, default and public access specifiers?
38) What are this and super keywords?
39) What are transient and volatile keywords?
41) ***************Are all the classes specified in import statement actually imported?
42) Can an inheritance relationship exist between two interfaces?
46) What is the meaning of various keywords specified in creating the main method?
47) What is  the purpose of ^ operator?
48) What is the difference between pass by value and pass by reference?
49) ***************What are the various types of inner classes?
50)*************** What are the various memory areas in JVM and what kind of information is stored in each of them?

Phone screen questions : 
Given a domain model, describe the process you follow to create a service.
Expect to hear: UML (class & interaction diagram), Data Model, SQL/DDL, API definition & documentation, Interface, Unit tests, integration tests.
How do you test your services?
Expect: JUnit, TestNG, or similar. Unit & integration tests, test cases.
Describe how you have used the Spring Framework.
Expect: IOC, JDBC Templates, controllers, annotations.
Describe your experience with high-volume website development.
Describe how you have addressed scalability/performance issues with large datasets.
Describe the approach you use to analyze performance issues. (Service API down.) (Web tier)
Expect to hear: profiler, SQL explain plan, debugger
What's the latest version of Java you have used. What, if any, changes did you take advantage of?
What's the latest version of Spring you have used. What, if any, changes did you take advantage of?
Describe the build systems you have used.
Expect: Ant, Maven, other.
Have you used any continuous build systems?
Expect: Cruise control, Hudson, other.
Which sounds like the most fun(Optional):
Refactoring some code that has bothered you for a long time.
Designing a new service API
Creating an AJAX based form processing framework.
Creating an automated testing/performance framework.
Porting a legacy application to your favorite language
===================================================================== 
  • What are the 4 basics of OOP?
  • Define Data Abstraction. What is its importance?
  • Given a cube of size n*n*n (i.e made up of n^3 smaller cubes), find the number of smaller cubes on the surface. Extend this to k-dimension.
  • What is the time and space complexities of merge sort and when is it preferred over quick sort?
  • Write a function which takes as parameters one regular expression(only ? and * are the special characters) and a string and returns whether the string matched the regular expression.
  • Explain polymorphism. Provide an example.
  • Given an array all of whose elements are positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array. So 3 2 7 10 should return 13 (sum of 3 and 10) or 3 2 5 10 7 should return 15 (sum of 3, 5 and 7)
  • You are given some denominations of coins in an array (int denom[])and infinite supply of all of them. Given an amount (int amount), find the minimum number of coins required to get the exact amount. What is the method called?
  • What is the difference between an object and a class
  • you are provided with a stream of numbers, design a data structure to store the numbers in the stream along with their no. of occurrences.ans:I told him to use a Trie and he asked me why not BST, and asked me to compare both..
  • Given two sorted arrays A1 and A2, of lengths L1 and L2 , L1 < L2 and the last L1 slots in A2 are vacant, get me all the numbers in A2, sorted in the most efficient manner without using extra space. This was a written test question in which I blabbered quick sort will do.......In fact the answer was merge sort. I misunderstood the question a bit and was thinking in some other direction. But after he clarified the question, I wrote the code immediately.
  • In an array of size n, there is one number missing and one number repeated twice. Find them.I was a fool not to notice the sum of numbers and sum of squares of numbers property immediately. But after getting a clue, I answered it.
  • What is the effect by keeping a constructor private? (in terms of inheritance),
  • Say you are using a map in your program, how would you count the number of times the program use put() and the get() function? How would you do that if its using multiple maps in the program? How would you do that if the map is sent as a parameter in a method? How would you do it if the multiple maps are passed into the methods (as parameters), and are use differently? (it went on forever….)
  • What do you know about Java generics
  • what is object reflection in Java
  • What is polymorphism.
  • Design an OO parking lot. What classes and functions will it have. It should say, full, empty and also be able to find spot for Valet parking. The lot has 3 different types of parking: regular, handicapped and compact.
  • Coding: I have an integer array where every number appears even number of times and only one appears odd times. Find the number.(I said hashtable and he asked me to write code with Hashtable)
  • What data structure would you use to look up phone numbers for customer names.(I said Hashtable. Asked why hashtable, why not a tree. I said HT has O(1). Asked is order always 1, when more than O(1) in HT.
  • Data Structures: How will you use a hashtable to find data in a tree. (Then he rephrased) suppose I have a hashtable, I want to store the data in a tree instead of a bucket. How will I do it. What complexity to find an element.
  • Bits & Bytes: Find if a binary representation of a number is palindrome. The function should work irrespective of number of bytes for an integer. Suppose if our machine is 4 bytes for an int, how will you use the program for 8 byte machine.
  • What is the flaw in the design of Java.lang.Stack class of Java
  • What is the use of volatile variable.Explain it in Singleton class also for lazy initialization.
  • How to implement your own HashMap in java
  • Why should you not make your Sinleton claas as Serializable and Clonable.
  • What is the limitation of singleton pattern
  • Why Java language designer has chosen to make all the variable inside an Interface as public ,static and final.
  • What are the various ways in singleton pattern can be made to fail and how to avoid them ?
  • The wrapper classes also offer utility methods for converting to and from the int values they represent. Thus if you have a string that could also represent a number, you can use a wrapper class to perform that calculation.
  • I have a class A which implements serializible and there are two sub classes B and C which extends A. I want clsss B not be serializible ? How can I achive it?                                                          Refer  :http://www.careercup.com/question?id=7508689
  • Why do we need thread class when we have Runnable interface ? http://www.careercup.com/question?id=7571666
  • Name all the memories which are available in JVM? I knew only heap and perm. Is there any other memory also? http://www.careercup.com/question?id=7547664
  • What intern method does in java?  http://www.roseindia.net/java/string-examples/string-intern.shtml http://www.careercup.com/question?id=7184154
  • what is daemon thread in java? daemon thread is a low priority thread that is terminated as soon the vm exits. It is generally used to do all the house keeping work like gc thread is a daemon thread.It can be set using thread.setDaemon(true); And then start the thread.  The main thread terminates it if it is finished.
  • What is Java Reflection API? Java reflection supports dynamic retrieval of information about classes and data structures by name, and allows for their manipulation within an executing Java program.
  • What is the difference between Serializable and Externalizable interfaces ?  http://www.careercup.com/question?id=3220676
  • Given a sorted array of n integers that has been rotated left or right by k places, give an algorithm that searches and finds an element in the array in log n time.   Example Input : 8 9 0 1 2 4 5 6 (sorted array rotated right by 2 places)http://www.careercup.com/question?id=2319661
  • What are features of optimum Java code : reusability/modularity,  data/functional abstraction,  complete code coverage,  fail-safe (crashes safely.. no one can totally avoid crashing).. most imp of all.. meet the user requirements.. add more if needed. Takes care of garbage collection.
  • Explain what is in a deployment descriptor file? give an example of a deployment descriptor ?           A deployment descriptor contains configuration data that the run-time environment uses for an application. A deployment descriptor can include information about the following:
               * The structure and content (enterprise beans or servlets, for example) of the application.

              * References to internal and external dependencies of the application. For example, an enterprise bean in an EJB module can require another enterprise bean that is not bundled in the same module.

            * References to resource factory objects, such as URLs, JDBC DataSources, JavaMail Sessions, JMS Connection Factories, JMS Destinations, and J2C Connection Factories.

        * Security roles that the container uses when implementing the required access control for the application.

        * Transactional information about how (and whether) the container is to manage transactions for the application.


  • How does the Collections API handle collisions? How does the API handling making the collection "some-what" collision safe?Explain- which collection does this affect and the best way to deal with it.Also explain, the most common scenario that causes this issue- hint* one is in threading(how can this be caused). Refer for discussion : http://www.careercup.com/question?id=417089
  • Can Java constructor has private or protected access type?                                                        Refer : http://www.careercup.com/question?id=296844
  • Write a Java program that prints the size of a non-primitive Java object.
  • What is the default visibility of an instance variable in java? What is package visibility?
  • What is the use of volatile variable?  http://www.careercup.com/question?id=2726
  • Why should you not make your Singleton class as Serializable and Clonable?http://www.careercup.com/question?id=2711
  • implement a counting semaphore in Java? http://www.careercup.com/question?id=133664
  • write java code for prime number generation?
  • What is the limitation of singleton pattern? http://www.careercup.com/question?id=2789
  • Why is access to static variables not allowed from non-static methods in java?http://www.careercup.com/question?id=2462
  • What is Garbage Collection in Java. How is it implemented? What kind of algorithms does the garbage collector use? How does it know that references can be collected? What are advantages and disadvantages of garbage collection? http://www.careercup.com/question?id=3111
  • How does Java achieve synchronization? Given an class with Synchronized method A and B, a normal method C, there are 2 threads, one instance, can these two threads call A at the same time? call A and B at the same time? A & C at the same time? http://www.careercup.com/question?id=57337
  • You are using a map in your program, how would you count the number of times the program use put() and the get() function? How would you do that if its using multiple maps in the program? How would you do that if the map is sent as a parameter in a method? How would you do it if the multiple maps are passed into the methods (as parameters), and are use differently? (it went on forever....)http://www.careercup.com/question?id=58095

Tomcat webserver

Tomcat is an open source web server developed by Apache Group. Apache Tomcat is the servlet container that is used in the official Reference Implementation for the Java Servlet and JavaServer Pages technologies. The Java Servlet and JavaServer Pages specifications are developed by Sun under the Java Community Process. Web Servers like Apache Tomcat support only web components while an application server supports web components as well as business components (BEAs Weblogic, is one of the popular application server).To develop a web application with jsp/servlet install any web server like JRun, Tomcat etc to run your application.

Web server and application server : A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send or redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-side technology. Whatever their purpose, such server-side programs generate a response, most often in HTML, for viewing in a Web browser.
           The web server simply passes the request to the program to handle it. The web server does not provides any functionality beyond providing an environment in which the server - side program can execute and pass back the generated responses. The server-side program usually provides such functions as transaction processing, database connectivity and messing .
Application Server :
While an application server exposes business logic to client applications through various protocols like HTTP, TCP-IP etc. All the web servers mainly deals with sending HTML for displaying to a Web browser. An application server providers allows the client to access the business logic for use. The application server is used to run business logic or dynamically generating presentation code. A J2EE application server runs servlets and JSPs that are used to create HTML pages dynamically. In this case, J2EE application server can run EJBs ? which are used to execute business logic. An application server is more capable of dynamic behaviour than webserver.

Refer : http://en.wikipedia.org/wiki/Apache_Tomcat

SVN

Basic svn commands : 
#create new repository
svnadmin create d:/svn/project

#import project to repository
svn import d:/web/home/project/www/ svn://localhost/

#checkout working copy from repository
svn co svn://localhost/ d:/web/home/project/www/

#update working copy
svn update d:/web/home/project/www/

#add ( delete, copy, move ) a folder or file
svn add d:/web/home/project/www/new

#find changes
svn status d:/web/home/project/www/

# revert file to his initial state in working copy
svn revert d:/web/home/project/www/index.php

# commit change to repository
svn commit d:/web/home/project/www/ -m "change description"

SVN status codes : http://blog.gotofritz.net/howto/svn-status-codes/

Refer : http://amukukki.blogspot.in/2008/07/basic-svn-commands.html

Comparison of svn and cvs :
 http://www.skill-guru.com/blog/2010/08/25/comparin-svn-and-cvs/
http://www.pushok.com/software/svn-vscvs.html

JMX


JMX is a technology that lets you implement management interfaces for Java applications.

A management interface, as defined by JMX, is composed of named objects - called MBeans (Management Beans). MBeans are registered with a name (an ObjectName) in an MBeanServer. To manage (a) resource(s) in your application, you will write an MBean that defines its management interface, and then register that MBean in your MBeanServer.
The content of the MBeanServer can then be exposed through various protocols, implemented by protocol connectors, or protocol adaptors.

A protocol connector (e.g. the JMX RMI Connector) exposes the MBeans as they are - so a remote client sees the same model than a local client.
A protocol adaptor (e.g. an SNMP adaptor, or HTML adaptor) performs (or provides hooks to let you perform) a model mediation - to adapt the model to what a client of that protocol (e.g. SNMP Manager, or Web Browser) would expect to see.

Refer : https://blogs.oracle.com/jmxetc/entry/what_is_jmx
http://en.wikipedia.org/wiki/Java_Management_Extensions

Code review

Code review guide lines
11_Best_Practices_for_Peer_Code_Review.pdf

Which things instantly ring alarm bells when looking at code?
Q)
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.
This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another
Ans)
When grading a student's program, I can sometimes tell in a "blink"-style moment. These are the instant clues:
  • Poor or inconsistent formatting
  • More than two blank lines in a row
  • Nonstandard or inconsistent naming conventions
  • Repeated code, the more verbatim the repeats, the stronger the warning
  • What should be a simple piece of code is overly complicated (for example, checking the arguments passed to main in a convoluted way)
  • unreachable code
  • commented code
Rarely are my first impressions incorrect, and these warning bells are right about 95% of the time. For one exception, a student new to the language was using a style from a different programming language. Digging in and re-reading their style in the idiom of the other language removed the alarm bells for me, and the student then got full credit. But such exceptions are rare.
When considering more advanced code, these are my other warnings:
  • The presence of many Java classes that are only "structs" to hold data. It doesn't matter if the fields are public or private and use getters/setters, it's still not likely part of a well thought-out design.
  • Classes that have poor names, such as just being a namespace and there's no real cohesion in the code
  • Reference to design patterns that aren't even used in the code
  • Empty exception handlers without explanation
  • When I pull up the code in Eclipse, hundreds of yellow "warnings" line the code, mostly due to unused imports or variables
  • Check the scope of access modifiers.
In terms of style, I generally don't like to see:
  • Javadoc comments that only echo the code
These are only clues to bad code. Sometimes what may seem like bad code really isn't, because you don't know the programmer's intentions. For instance, there may be a good reason that something seems overly complex-- there may have been another consideration at play.

Monday, March 5, 2012

Quartz job

Batch solutions are ideal for processing that is time and/or state based:
Time-based: The business function executes on a recurring basis, running at pre-determined schedules.
State-based: The jobs will be run when the system reaches a specific state.
Batch processes are usually data-centric and are required to handle large volumes of data off-line without affecting your on-line systems. This nature of batch processing requires proper scheduling of jobs. Quartz is a full-featured, open source job scheduling system that can be integrated with, or used along side virtually any Java Enterprise of stand-alone application. The Quartz Scheduler includes many enterprise-class features, such as JTA transactions and clustering.

The following is a list of features available:
Can run embedded within another free standing application
Can be instantiated within an application server (or servlet container).
Can participate in XA transactions, via the use of JobStoreCMT.
Can run as a stand-alone program (within its own Java Virtual Machine), to be used via RMI
Can be instantiated as a cluster of stand-alone programs (with load-balance and fail-over capabilities)
Supoprt for Fail-over
Support for Load balancing.
Scheduling jobs using Quartz or Timer
Scheduling and Thread Pooling
CronTrigger Tutorial

MVC Architecture

Model/view/controller (MVC) is a software architecture, currently considered an architectural pattern, used in software engineering. The pattern isolates "domain logic" (the application logic for the user) from the user interface (input and presentation), permitting independent development, testing and maintenance of each (separation of concerns).
Use of the Model/View/Controller (MVC) pattern results in applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.

The main aim of the MVC architecture  is to separate the business logic and application data from the presentation data to the user.

Refer : http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
http://www.roseindia.net/struts/mvc-architecture.shtml
http://www.jcorporate.com/expresso/doc/edg/edg_WhatIsMVC.html

Web services

The term Web services describes a standardized way of integrating Web-based applications using the XML, SOAP, WSDL and UDDI open standards over an Internet protocol backbone. XML is used to tag the data, SOAP is used to transfer the data, WSDL is used for describing the services available and UDDI is used for listing what services are available. Used primarily as a means for businesses to communicate with each other and with clients, Web services allow organizations to communicate data without intimate knowledge of each other's IT systems behind the firewall
.
Unlike traditional client/server models, such as a Web server/Web page system, Web services do not provide the user with a GUI. Web services instead share business logic, data and processes through a programmatic interface across a network. The applications interface, not the users. Developers can then add the Web service to a GUI (such as a Web page or an executable program) to offer specific functionality to users.
Web services allow different applications from different sources to communicate with each other without time-consuming custom coding, and because all communication is in XML, Web services are not tied to any one operating system or programming language. For example, Java can talk with Perl, Windows applications can talk with UNIX applications.
Web services do not require the use of browsers or HTML.
Web services are sometimes called application services.

              Web Services can convert your application into a Web-application, which can publish its function or message to the rest of the world.The basic Web Services platform is XML + HTTP.

DBCP Connection pooling

Many Apache projects support interaction with a relational database. Creating a new connection for each user can be time consuming (often requiring multiple seconds of clock time), in order to perform a database transaction that might take milliseconds. Opening a connection per user can be unfeasible in a publicly-hosted Internet application where the number of simultaneous users can be very large. Accordingly, developers often wish to share a "pool" of open connections between all of the application's current users. The number of users actually performing a request at any given time is usually a very small percentage of the total number of active users, and during request processing is the only time that a database connection is required. The application itself logs into the DBMS, and handles any user account issues internally.
There are several Database Connection Pools already available, both within Apache products and elsewhere. This Commons package provides an opportunity to coordinate the efforts required to create and maintain an efficient, feature-rich package under the ASF license.
The commons-dbcp package relies on code in the commons-pool package to provide the underlying object pool mechanisms that it utilizes.
DBCP now comes in two different versions, one to support JDBC 3 and one to support JDBC 4. Here is how it works:
DBCP 1.4 compiles and runs under JDK 1.6 only (JDBC 4)
DBCP 1.3 compiles and runs under JDK 1.4-1.5 only (JDBC 3)
DBCP 1.4 binaries should be used by applications running under JDK 1.6.
DBCP 1.3 should be used when running under JDK 1.4 or 1.5.
There is no difference in the codebase supporting these two versions, other than that the code implementing methods added to support JDBC 4 has been filtered out of the DBCP 1.3 sources.

BasicManagedDataSource : BasicManagedDataSource is an extension of BasicDataSource which creates ManagedConnections. This data source can create either full two-phase-commit XA connections or one-phase-commit local connections. Both types of connections are committed or rolled back as part of the global transaction (a.k.a. XA transaction or JTA Transaction), but only XA connections can be recovered in the case of a system crash.

BasicManagedDataSource adds the TransactionManager and XADataSource properties. The TransactionManager property is required and is used to elist connections in global transactions. The XADataSource is optional and if set is the class name of the XADataSource class for a two-phase-commit JDBC driver. If the XADataSource property is set, the driverClassName is ignored and a DataSourceXAConnectionFactory is created. Otherwise, a standard DriverConnectionFactory is created and wrapped with a LocalXAConnectionFactory.

Refer : http://vigilbose.blogspot.in/2009/03/apache-commons-dbcp-and-tomcat-jdbc.html
http://commons.apache.org/dbcp/configuration.html