Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, 31 May 2013

Configure an alternate JAVA

Get the new JDK and put it in /usr/liv/jvm and run this commands

$ update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk-7u21/bin/java" 1
$ update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk-7u21/bin/javac" 1
$ update-alternatives --install "/usr/bin/javaws" "javaws" "/usr/lib/jvm/jdk-7u21/bin/javaws" 1

$ chmod a+x /usr/bin/java
$ chmod a+x /usr/bin/javac
$ chmod a+x /usr/bin/javaws
$ chown -R root:root /usr/lib/jvm/jdk-7u21

Make sure you read the below command output clear and choose which Java you want.
$ update-alternatives --config java
There are 2 alternatives which provide `java'.

  Selection    Alternative
-----------------------------------------------
 +        1    /usr/lib/jvm/java-6-openjdk/jre/bin/java
*         2    /usr/lib/jvm/jdk-7u21/bin/java

Press enter to keep the default[*], or type selection number: (If you want java 6, write 1 and if you java 7 write 2)

* This commands are being good in debian/ubuntu system. I am not sure about Red Hats/CentOs

Tuesday, 13 December 2011

Linux CPU/Memory Utilization - Tips/Tricks/Commands

As a common knowledge CPU is been allocated to multiple process in a round robin algorithm with a certain time slicing. But when any process starts consuming the CPU and not releasing due to heavy computation either in quality (depth of computation) or quantity, system's load average will increase causing other process to wait in the queue to get the CPU. This may cause in some deadlock, system CPU hogging. I am gonna share my experience on how to fix such issues on linux servers and more tricks around web systems.

Few command to figure out the CPU usages
$ top 
This will tell you overall usage, Make sure that you notice the load average. If load average is going more than 2 to 3, means system CPU is getting utilized a lot.
Second observation is the process, check the processes who is coming on the top and specially whose %CPU is printing out to be high in number, higher the value that particular program is consuming more CPU.

$ mpstat
Use this command to see the CPU utilization individually

$atop
Use this command to see the CPU utilization of every processor (or cores)

$ apt-get install sysstat
Install this package to track the system usages on regular intervals

$sar
This will show you history of CPU utilization, using which you can track when the CPU usage or IO wait was high

$sar -u 2 10
Prints the current system usages in every 2 seconds and repeats for 10 times
  • %user: Percentage of CPU utilization that occurred while executing at the user level (application).
  • %nice: Percentage of CPU utilization that occurred while executing at the user level with nice priority.
  • %system: Percentage of CPU utilization that occurred while executing at the system level (kernel).
  • %iowait: Percentage of time that the CPU or CPUs were idle during which the system had an outstanding disk I/O request.
  • %idle: Percentage of time that the CPU or CPUs were idle and the system did not have an outstanding disk I/O request.

Who is the hell is eating the CPU
$ ps -eo pcpu,pid,user,args | sort -k 1 -r 
Prints all the processes in reverse sorted order of consuming CPU

$ ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10
Prints the most consuming process in reverse order and limits to 10 size

$iostat
To prints the statistics of IO usage since system reboot

$iostat -xtc 2 10
Prints the IO usage in every 2 seconds for 10 times

Check Memory Usages

ps aux | awk '{print $2, $4, $11}' | sort -k2r | head -n 10
Prints the which process is consuming how much memory

You can see the free and available memory using commands like
$free
$atop

---
Some concepts to resolve the common issues in web system.
1. Most of the time IO wait will be high on server to cause the server to be slow, so check the slow query log in DB and resolve such queries, try to optimize the mysql usage with caching/indexing

2. Make sure that tomcat or given enough memory and GC parameters to use the memory efficiently
Like this (as a Java runtime variables)
java -Xms512M -Xmx512M -Xss128K -XX:PermSize=64M -XX:MaxPermSize=128M -XX:NewRatio=4 -XX:+HeapDumpOnOutOfMemoryError -verbose:gc -XX:+PrintGCTimeStamps -XX:+PrintGCDetails -Djava.awt.headless=true -jar xyz.jar

3. $jmap -histo:live process_id
Command to check the memory usage by a Java process - keep and eye that you are not loading too many objects in memory by mistake

4. $jstack process_id
Command to check java process running stack traces - keep and eye to watch any regular method exception is coming which is taking more time to execute(resolve that method execution, optimize it)

Wednesday, 4 May 2011

Make your development system up on Mac

This post is about persisting the experience while installing Mac 10.6.3 (SnowLeopard) on my personal computer.

First of all you should decide if you want to install by using binary then I have no idea. I can tell you to install so many things easily using MacPort software manager.

So first of all follow this link to download and install MacRport http://www.macports.org/install.php

Basic command usages for MacPort
---------------------------
port list variant:no_ssl
port uninstall name:sql
port echo depof:mysql5
port echo apache*
port install mysql5
--------------------------

Now you need Apache + PHP + Mysql
Step 1: sudo port selfupdate
Step 2: sudo port install gawk
Step 3: sudo port install nawk (For me this step was failed, but I gave a damn !!!)
Step 4: sudo port install php5 +apache2 +mysql5-server

Now use the command below to setup the mysql db.
$ sudo /opt/local/lib/mysql5/bin/mysql_install_db --user=mysql

You can change mysql root password using this command
$ /opt/local/lib/mysql5/bin/mysqladmin -u root password 'new-password'

Next, you can configure apache and mysql to start automatically by enter the command below:-
$ sudo launchctl load -w /Library/LaunchDaemons/org.macports.apache2.plist
$ sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist

Now you need to configure apache to load php file, open /opt/local/apache2/conf/httpd.conf and add this 2 line:-
LoadModule php5_module modules/libphp5.so
AddType application/x-httpd-php .php

Once saved, you may restart your apache

To start your apache2 and mysql5 manually, type the command below:-
$ sudo /opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper start
$ sudo /opt/local/etc/LaunchDaemons/org.macports.mysql5/mysql5.wrapper start


Now you'll want Java
Java is usually installed with Mac OS and XCode (and yes you need to install XCode at the very very first thing of above all, you can locate XCode in any of your given DVD with Mac, or you can download also). You can usually find java and javac commands are usually working. The working java home would be usually at /Library/Java/Home

Eclipse : Download it from here http://eclipse.org/downloads/

Tomcat :
Step 1: Download it from here http://tomcat.apache.org/download-60.cgi
Step 2: After downloading tomcat, extract the file and go to bin
Step 3: Create a file setenv.sh and write this line JAVA_HOME=/Lbrary/Java/Home (or whatever java home you have)
Step 4: Save the file, and run "chmod 777 setenv.sh" and you are ready with tomcat
Step 5: ./startup.sh will run the tomcat, you can see the log at ~tomcat_home/logs/catalina.out

Tuesday, 11 November 2008

Servlet, JSP


1. What are methods of Servlet and Why the servlet has init() method?Servlet is Basic interface that contains these methods
  1. init(ServletConfig)
  2. service(ServletRequest, ServletResponse)
  3. destroy()
  4. getServletConfig()
  5. getServletInfo()

Then implemented abstract classes are GenericServlet and HttpServlet.
Now constructor can not be define in interface, but init can have as skeleton in interface,
so any servlet using the interface knows that what need to be override to initialize a servlet.

Q. which pattern is this? Templating pattern

2. What is necessary to override init() method of Servlet?
There are no necessary conditions to override this particular method. In case you are overridding init(ServletConfig config), then make sure to call super.init(config).

3. Context Object pattern
A context object encapsulates web server specific HTTP information in more general and portable
form. It is used when:
  1. you have components and services that need access to the system information.You want to decouple application components and services from the protocol specifics of system information.
  2. you want to expose only relevant APIs within a context.
  3. Use a context object to encapsulate state in a protocol-independent way to be shared throughout your application.
4. Life cycle of servlet and jsp
Servlet : init(), service(), destroy()
JSP: translation, and above all

5. Difference between in static and dynamic include
  1. The syntax for static include is and the syntax for dynamic include is
  2. Static include is an inline inclusion. i.e., the contents of the file will be included at translation phase. It’s something like a copy and paste. In case of dynamic include the response of the file will be included to the original response at runtime. The file will be processed separately and only the response will become the part of the original files’ response.
  3. Static include cannot have a dynamic filename. This is because the servlet container needs the files for inclusion, at translation phase itself. 
  4. Static include cannot accept a parameter dynamic can.
  5. Static includes are faster than dynamic includes.
  6. In case if the resource lost occurs, container will throw 500(Internal Server Error) for static, though 404(Page Not Found Error) for dynamic include

6. Difference between forward and sendRedirect
  1. When you invoke a forward request, the request is sent to another resource on the server, without the client being informed. This process occurs completely within the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. 
  2. In case of sendRedirect browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. 
  3. Redirect is slower than forward
  4. forward is method of RequestDespatcher and sendRedirect is of request 
7. Inversion Of Control (IoC) and Dependency Injection (DI) are concepts generally associated with the Spring Framework.  The easiest way to think of Inversion Of Control is what Rod Johnson (founder of the Spring framework) calls the Hollywood Principal, "don't call us we'll call you:.  IoC uses interfaces to acquire and release resources a prime example being JDBC connections.  This also part of the reason Spring works so well with Object/Relational Mapping (ORM) tools such as Hibernate, iBatis, and TopLink.

DI is a more specific version of IoC.  DI pushes application dependencies at runtime.  DI comes in several flavors in Spring:
    1.  Setter Injection - uses Java Bean setters (and getters) to get dependencies
    2.  Contructor Injection - dependencies come from constructor arguments
    3.  Method Injection - where the container is used to implement dependencies


8. Explain Struts navigation flow


When we deploy our application in the server, at first the container reads the information from web.xml file.Here ActionServlet object will be created and init() of ActionServlet will be called.Here ActionServlet is the backbone to the whole application.
When client send a rewuest using .jsp extension , getters() and reset() of FormBean will be called. When client fill the form and press on submit button, then setters() and validate() will be called.
If the data is not valid ,then the form redirects to another page which is specified in struts-config.xml file. If the data is valid , then only Action class object will be created.

In Action class , have execute() which have return type of ActionForward. We can specify the business logic in Model and provide that object in execute(). After completion of business logic execution , then it forwards to another page ( either success or failure) , whichis specified in struts-config.xml file.
Action classes of struts uses Command pattern and overall as a web flow, it uses MVC pattern.

Friday, 31 October 2008

Java concepts

4.  JVM with version
version 4 - Autoboxing (wrapping primitive to objects automaticaly) and Unboxing
Version 5 - Generic/Templating, Iterator, You can create array by using triple dot ...
  - static import,  import static 
Version 6 - No Idea yet
Version 7 - Closure(Functions inside functions and functions will have a reference)

7. Serialization (Usages)
1. persistence 
2. copy mechanism
3. communication mechanism

8. Cloning: 
Deep and sallow cloning:

Thought: while doing deep cloning, copy of the object might we can not copy all the objects so easly,  so serilize it and deserilize it
   How to serilize and deserialize and object?
   Sample code:
Contact  myObject = new Contact();
System.out.println("Previous: "+myObject);
ByteArrayOutputStream fos=new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(myObject);
oos.flush();
oos.close();
byte[] array=fos.toByteArray();
ByteArrayInputStream fis=new ByteArrayInputStream(array);
ObjectInputStream ois = new ObjectInputStream(fis);
Contact myDeserializedObject = (Contact)ois.readObject();
ois.close();
System.out.println("After: "+myDeserializedObject);

   
9. How to make a class immutable?
1. make all variable private
2. no setter methods
3. in getter method, two things should be there
1. either we return the copy of the class variables
2. or we return a an object of class which is immutable again, like string
4. in constructor also we don't assign class variable directly to passed variables, it should copy the content

Sample questions on String immutability
String s1="abc";
String s2="abc";
s1.equals(s2), true
s1==s2, true
String s3=new String("abc");
s1.equals(s3), true
s1==s3, false

10. Why do we need to extends RuntimeException class?
Answer is consistency in approach, 
There are two basic type of exception, application exception(checked) and system exceptions (unchecked) So when we feel that some exception need not to reach to use, we'd like to wrap that in a system exception. There should be two base Exception classes, one for each and should be use whenever relevent exceptions are thrown. When SQLException is thrown, we wrap it in a custom system exception and throw it, note: checked is been converted in to unchecked.

11. Can we declare a class as static?
Top level calsses can not be declared as static, compiler error.
Inner classes can be, and it act as a static object of outer class. Static inner classes imply that the object of the inner class is not dependent upon the outer class object and can exist indepenently.
Now there are four types of Inner classes.
1. Anonymous: since Anonymous classes have not got proper class declration,     no possibility of making it static
2. Local : Local classes are the same as local variables, local classes aren't allowed to be declared public, protected, private, or static.
3. Member: The member class is the only class that you can declare static. When you declare a member class, you can instantiate that member class only within the context of an object of the outer class in which this member class is declared. If you want to remove this restriction, you declare the member class a static class.
4. Nested top-level. A nested top-level class is a member classes with a static modifier. A nested top-level class is just like any other top-level class except that it is declared within another class or interface.

JDBC

Four JDBC driver types.

Type 1: JDBC-ODBC Bridge plus ODBC Driver:
The first type of JDBC driver is the JDBC-ODBC Bridge. It is a driver that provides JDBC access to databases through ODBC drivers. The ODBC driver must be configured on the client for the bridge to work. This driver type is commonly used for prototyping or when there is no JDBC driver available for a particular DBMS.

Type 2: Native-API partly-Java Driver:
The Native to API driver converts JDBC commands to DBMS-specific native calls. This is much like the restriction of Type 1 drivers. The client must have some binary code loaded on its machine. These drivers do have an advantage over Type 1 drivers because they interface directly with the database.

Type 3: JDBC-Net Pure Java Driver:
The JDBC-Net drivers are a three-tier solution. This type of driver translates JDBC calls into a database-independent network protocol that is sent to a middleware server. This server then translates this DBMS-independent protocol into a DBMS-specific protocol, which is sent
to a particular database. The results are then routed back through the middleware server and sent back to the client. This type of solution makes it possible to implement a pure Java client. It also makes it possible to swap databases without affecting the client.

Type 4: Native-Protocol Pur Java Driver
These are pure Java drivers that communicate directly with the vendor’s database. They do this by converting JDBC commands directly into the database engine’s native protocol. This driver has no additional translation or middleware layer, which improves performance tremendously.


1. Is there any limitation for no of statments executed with in batchupdate?

No, any number of statements we can write in the batch update but all the updates only means (insert,delete,update) not select

2. What happens when we execute "Class.forname("Driver class name");"

By the end of the execution of Class.forName("Driver
class"); the driver class should be loaded into the memory
but also
1. The driver class should be initialized
2. Should be registered with the driver manager class

The above two operations are not done by forName() . So a pure Static() block is defined in which the above two tasks are manipulated and by which we are able to get connection, immediately after loading the driver class without writing any code to initialize the driver class.


3. What are the Statements in JDBC?

1. Statement: Each time you fire a query it compile and executes and returns the result set
2. PreparedStatement: It parses, compile and optimize the query and keep it, next time when query fired, it picks the compiled query and excute. Also you send dynamic sql statements.
3. Callable Statement: To execute stored procedure like pl/sql