Sunday, 19 May 2013

Tibco Tutorials for beginners


This Tibco Tutorial is collection of all my previous Tibco rendezvous and Tibco EMS tutorials. I have written this compilation post to provide all tibco tutorials at one place for easy navigation and access. Anyone who is started working on Tibco on any investment bank or brokerage house for there electronic trading systems or algorithmic trading system can benefit from these tibco tutorials because these are based on my experience in stock trading systems which uses Tibco Rendezvous for all there Front-End backend communication. Tibco Certified messaging is used by Electronic trading system or Order Management system to receive orders and Send Execution in FIX Protocol.

TIBCO Rendezvous Tutorial


TIBCO Tutorial 1: TIBCO Rendezvous or TIBCO RV messaging

Today I am going to share some of my experience while working with TIBCO RV , this is standard product used in most of the global banks for messaging, its great product which offers following benefits:

  •     location transparency
  •     platform independence
  •   reliable and fast
  •    comprehensive API
  •     Point to point delivery and publish/subscribe delivery.
Location transparency
Location transparency means for sending and receiving message on a multicast network you need not to aware of physical location of sender or receiver as long as you know the topic (also called subject in TIBCO world), so its pretty simple Sender publish message on multicast topic in a network and all subscriber which have subscribed on that topic receives message without being knowing physical location of publisher.

Sender could be anywhere in the world e.g. New York, Tokyo, London, receiver can be anywhere e.g. London, Hong Kong or Tokyo.


Platform independence
TIBCO Rendezvous or TIBCO RV doesn't depend on platform, Sender can be running on UNIX box while receiver could be running on windows machine. Most of the time GUI runs on windows and server runs on Linux and they exchange messages via TIBCO.
To read full article please see TIBCO Rendezvous messaging.

TIBCO Tutorial 2: Fundamentals of Tibco RV messaging.

Main purpose of these Tibco tutorials is to give overview of fundamentals of Tibco RV with day to day examples and discuss its usage. I have been using Tibco for more than 3 years and have used in my various project where I use Tibco reliable messaging, Tibco certified messaging for both client to server and server to server communication.

"Tibrvsend" and "tibrvlisten" these are two utility comes with every Tibco installation. One can used to send message on any multicast network while other can be used to receive message on any multicast network.

Here is an example of sending and receiving message in Tibco multicast network.

tibrvsend -network "190.231.54.20" -service "5420" -daemon "tcp:7500" "TESTING”

tibrvlisten -network "190.231.54.20" -service "5420" -daemon "tcp:7500"


So here we see three new things Tibco network, service and daemon

Network
------------
This is the multicast network on which message will travel here it is "190.231.54.20"
It could be any IP  address which is setup on your network router. If your computer has multiple NIC (network interface card) then eth0 or eth1 could be prefixed in network e.g.'
"eth0; 190.231.54.20"

normally different NIC card is used for different network speed e.g. eth0 could be a Gigabyte network or eth1 could be for Megabyte network.


Service
----------
This is the UDP port on which Tibco rv sends message, its advised to

To read full article please see How to troubleshoot FIX Connectivity issues.

Tibco Tutorial 3: Tibco Rendezvous tips and commands

tibco rendezvous tutorial, tibco ems and tibco rvBefore writing these "Tibco tutorial" series I looked for some introductory simple Tibco tutorial which explains concept of Tibco Rendezvous in simple word and give us working knowledge of Tibco but I did not found any. Tibco is most heavily used middleware solution on enterprise world and form backbone of many large enterprise including global banks.

These are few tips/commands/concept which essential while working with Tibco RV for resolving day to day problems or issues.

How to send message from command prompt using tibrvsend?
tibrvsend -network "190.231.54.20" -service "5420" -daemon "tcp:7500" "TESTING”



How to receive message in command prompt using tibrvlisten ?
tibrvlisten -network "190.231.54.20" -service "5420" -daemon "tcp:7500" 

To read full article please see Tibco Rendezvous tips and commands.


Tibco Tutorial 4: Certified Messaging in Tibco Rendezvous

This is in continuation of my previous Tibco tutorial. Tibco Rendezvous  is most widely used middleware in enterprise world heavily used in banking and many global investment bank rely on Tibco Rendezvous for there high speed messaging requirement. its used by many trading application to receive high speed data e.g. Market data. in reliable mode Tibco provide reliable delivery of data but not guaranteed means if sender sends data to receiver via Tibco multicast network , Tibco tries best to deliver that data to receiver but there is no guarantee, data could be lost if receiver is too busy to receive it , if receiver is not running or receiver is hang. In some cases it’s possible to recover lost data by sending "Resend Request".

Resend Request is request which Receiver sends to Sender to resend lost data. If Sender has that data into memory it will resend but if it has already discarded then no way to recover that data and Tibco will issue DATALOSS Advisory. Sender will only keep data defined in "reliability" parameter while starting Tibco daemon and it normally ranges from 10-12 seconds.

Since reliable is good for high speed messaging where data becomes stale after few seconds and loss of some data didn't matter much e.g. in case of Market data where prices , quantity keeps changing.

But if you require guaranteed delivery where you don't want to lose any message you should consider option other that reliable messaging. Tibco provides a solution for this called "Certified messaging".

To read full article please see Tibco Certified messaging tutorial.

TIBCO Tutorial 5: Ledger file in Tibco Certified Messaging

This is in continuation to my previous article on TIBCO Certified messaging, in this TIBCO tutorial we will discuss about what is TIBCO ledger? What is process based ledger and what is file based ledger?  Which messages are stored in TIBCO ledger? What are advantage and disadvantage of using TIBCO ledger? When should we use Process based and File based ledger etc. if you would like to read my earlier TIBCO Tutorial please see.


TIBCO ledger file is used in case of certified messaging to store unresolved message. When you use certified messaging using CMTransport then rendezvous process will store of each message in a ledger which could be either in Memory or File based.
You can either opt for In Memory or Process based ledger or File based ledger both approaches has there advantage and disadvantages which we will discuss in this tutorial. In case if you are going to use In Memory or process based ledger than all unconsumed messages will be lost if process shutdown or crashed. so it only make sense to opt for Process based ledger if certification is required only on process duration if you would like to have recording after  process duration then file based ledger should be used.

TIBCO rendezvous Process keeps every outbound message in ledger either in Process memory or in persistent File based upon its configuration until it’s consumed by the entire certified subscriber or until specified expiry times got elapsed.

Advantage of File based ledger is that storage extends beyond process duration so message will be available even in case of process died which is

To read full article please see Tibco file based and memory based ledgers.

Tibco Tutorial 6: RVD vs RVRD (Rendezvous daemon vs Rendezvous Routing Daemon)

tibco rv tutorial, tibco tutorials

RVRD (Rendezvous Routing Daemon) are simply process owned by middleware or network teams which listens multicast traffic locally and transmit it to another RVRD counter part (another host) using TCP. This remote host than re multicast this traffic to there own network. So essentially it used to bridge two different regional networks e.g. London and New York etc.

RVRD is multicast in one end and unicast on other end so it receives messages from multiple RVD (Rendezvous Daemon) and send via TCP to another RVRD which distributes messages on different RVD (Rendezvous Daemon) on there own network e.g. say on NY network.

Control of RVRD (Rendezvous Routing Daemon) resides on middleware/network team and they decide which topics/subject is allowed for RVRD (Rendezvous Routing Daemon) traffic. So if you send message on a topic which is not configured on RVRD and subscriber for that service is on some another physical network it will not receive those messages until that topic is enabled on RVRD (Rendezvous Routing Daemon) front.

On the other hand RVD (Rendezvous Daemon) is a background process runs on every host which wants to send or receive message from Tibco multicast network. Your process depends upon this for reliable and efficient network communication. All messages go via RVD before it enters or leaves host on a multicast network and RVD (Rendezvous Daemon) is responsible for creating packets or assembling packets to and from the network.

To read full article please see difference between Tibco RV and Tibco RVD.

Tibco Tutorial 7: Tibrv Errors and Exceptions in Tibco Rendezvous

While working with Tibco rv during many years I found that Tibco errors are mysteriously difficult to diagnose for a newcomer and minor difference between syntax and semantics along with network specifics lead some strange error.
here I am putting most common error which I have faced mainly because of some silly mistake in syntax and spent hours to figure out exact cause during my initial days.

This list is by no means complete and I would encourage putting any other error you have encountered to make this list more useful.

Any suggestion, input feedback always welcome.

1) Error: Failed to initialize transport: Could not resolve network specification

This error comes when your rvd tries to creates Tibco transport and failed to created it , it could come in your Java program which is trying to establish Tibco transport or while using tibrvsend or tibrvlisten command . Recently I have encountered when I am trying to listen on a particular topic (subject) by using tibrvlisten command in my windows machine.

C:\>tibrvlisten -service "5420" -network "190.231.54.20" -daemon "tcp: 7500" TEST.REPLY

Cause: It was not working because of missing ";" before network value, when I modified network string as below it working.

C:\>tibrvlisten -service "5420" -network "; 190.231.54.20" -daemon "tcp: 7500" TEST.REPLY
To read full article please see Errors, Exception and issues on Tibco RV.

Tibco Tutorial 8: Difference between Tibco EMS and Tibco RV

Tibco RV stands for Tibco Rendezvous which is based on proprietary Tibco protocol (TRDP/PGM) developed by company. They have provided API in almost all major programming language and this is a preferred choice if you need high speed communication e.g. publishing market data updates etc. 
Most of the  stock trading application either equities or futures/options they are heavily relied on market data which they receive from various market data publishers e.g. Reuters , Bloom berg or Wombat but sometime format of market data is not something every application can directly consume so they have internal application which receives this stock prices and covert them into a format which every application can understand and here they publish market data in a Tibco multicast topic say MARKETDATA.TSE.UPDATE and all application which needs can subscribe to this.
While Tibco EMS stands for Tibco Enterprise Messaging service and is based upon JMS specification which is provided by Sun Microsystems. Though other JMS implementation also available e.g. MQ Series
To read full article please see difference between Tibco EMS and Tibco Rendezvous.

Tibco Tutorial 9: DATALOSS Advisory on Tibco RV

While working with TIBCO rendezvous you guys must have been faced problem of DATALOSS and might be aware of its severe consequences and in worst case how it can cause TIBCO Storm (A situation where TIBCO publisher bombards network with publishing so many messages and exhaust all network bandwidth of WAN links resulting in complete breakdown of network lines and communication). 

This Tibco Tutorial is in continuation of my Tibco Tutorial series and in this short TIBCO tutorial I will explain what DATALOSS in Tibco is and how we can minimize or prevent DATALOSS in Tibco RV.

To understand the DATALOSS in Tibco Rendezvous , what causes a DATALOSS in TIBCO RV and how we can prevent DATALOSS in TIBCO RV lets take a look back and see how exactly TIBCO Rendezvous or TIBCO RV works ?

TIBCO Rendezvous or TIBCO RV provides messaging solution, TIBCO publisher publishes message in a multicast network and TIBCO subscriber listens on same multicast network and on same service and a particular topic also referred as Subject. So whenever a message arrives on that service TIBCO daemon also referred as TIBCO rendezvous daemon see if subscriber has interest on any of incoming message if yes then it  delivers that message to the program. If program is too busy or very slow to process incoming message it would happen that some of the message expires and dropped at TIBCO RVD (rendezvous daemon) level and program will request retransmission of those messages.

To read full article please see what is Dataloss advisory on Tibco Rendezvous.

Tibco Tutorial 10: Introduction to Tibco Hawk

tibco rendezvous tutorial, tibco ems and tibco rv

This is another short TIBCO tutorial from my TIBCO tutorial series. in this i am going to discuss what is TIBCO hawk , Where do we use TIBCO hawk , What are components of TIBCO hawk , what benefit TIBCO hawk offers and how Tibco hawk works.  if you are interested to know more about TIBCO  Rendezvous , TIBCO EMS and there fundamental concept  or if you are looking for some TIBCO Interview questions you may find this link interesting TIBCO Tutorial

Lets start with TIBCO hawk now.
TIBCO Hawk is a monitoring tool which is used to manage distributed applications running across multiple servers or multiple geographic. you can use TIBCO hawk for reading log files and can have rules based upon certain keyword e.g. ERROR or Exception and when such word comes in log file it will alert the TIBCO hawk GUI also called TIBCO  HAWK Display. Hawk can also monitor whether a process is up or down etc.

TIBCO Hawk is based upon TIBCO RV and uses TIBCO Rendezvous or TIBCO RV capability for all its messaging requirements.

TIBCO hawk consists following functional components:

Hawk Agent: This is the most important part of whole TIBCO Hawk suite and has to be deployed  in all host you would like to monitor.
So a Hawk agent is a TIBCO Hawk process which performs all the monitoring and management tasks on the host as defined in the rule base.

To read full article please see tibco hawk tutorials for beginners.

Tibco Tutorial 11: Http Interface on Tibco Rendezvous

This is another post of my Tibco tutorial series, if you want to read more about Tibco RV or Tibco EMS please read there. In this post I am sharing you great tool to solve Tibco rv related problems and a great interface to analyze your Tibco RVD activities. Until i know this I mostly used netstat command to figure out which topics are subscribed by my Tibco RVD but after since I know about this I had helped me a lot.

Every host where Tibco RVD is running expose on HTTP interface using that we can get many useful information e.g.
--- How many clients are connecting to a particular service?
--- Which services has been subscribed by RVD

--- Which hosts are connected to this RVD (using remote daemon).

--- How much data has been sent to received
--- Viewing Tibco log to figure out any Tibco issue.
--- Hwo many subject a particular service is using and what are those etc.
To check on which Http port your rvd is publishing information do this in your Linux/windows host where RVD is running
To read full article please see Tibco Rendezvous Http interface.

Tibco tutorial 12: Reliability Parameter on Tibco Rendezvous

What is Reliability parameter of Tibco?
Message expiration depends on reliability parameter, the less the reliability parameter the message will expire quickly. Also reliability parameter is the time period for which server keeps the message which it has published.


How to change reliability parameter?

This is a startup parameter, you can see it by doing grep in ps –ef | grep rvd, for chaining it you need to disconnect all the application connected to that RVD and restart RVD daemon.


How to See the Reliability Parameter of Tibco RV which is running?

javin ps -ef | grep "rvd"

javin 20755     1  0 Jul07 ?        01:03:42 /opt/Tibcorv/7.5.4/bin/rvd_7.5.4 -listen tcp:7500 -http 7582 -no-permanent -reliability 20 -logfile /usr/tmp/rvd.log.localhost.javin -log-max-size 200 -log-max-rotations 10 -rxc-max-loss 40 -rxc-send-threshold 10000000

See here what reliability parameter on Tibco Rendezvous is .

Please share with your friends if like this article

How to escape text when pasting as String literal in Eclipse Java editor

Whenever you paste String in Eclipse which contains escape characters,  to store in a String variable or just as String literal it will ask to manually escape special characters like single quotes, double quotes, forward slash etc. This problem is more prominent when you are pasting large chunk of data which contains escape characters like a whole HTML or XML file,  which contains lots of single quotes e.g. ‘’ and double quotes “” along with forward slash on closing tags. It’s very hard to manually escape all those characters and its pretty annoying as well. While writing JUnit test for XML documents, parsing and processing I prefer to have whole XML file as String in Unit test, which pointed me to look for that feature in Eclipse. As I said earlier in my post Top 30 Eclipse keyboard shortcuts, I always look to find new shortcut and settings in Eclipse which help to automate repetitive task. Thankfully Eclipse has one setting which automatically escapes text as soon as you paste it. This is even more useful if you prefer to copy file path and just paste it, Since windows uses forward slash it automatically escape that instead of you going manually and escaping them. By default this setting is disabled in Eclipse IDE and you need to enable it.


How to enable automatic escaping while pasting text as String literal in Eclipse :

Here is the steps you need to perform to enable this setting in Eclipse which will automatically provide escaping required in Java for special characters like quotes, slashes etc.
2. Go to Windows --> Preferences --> Java --> Editor --> Typing 
3) check the check box "Escape text when pasting into a String literal" on section "In String literals.
This will escape text when pasted as String literal. Do it now, its an option worth enabling and I just wonder why not Eclipse IDE make this option enable by default. Believe me its extremely useful but same time hard to discover. Here is a screen shot of this option.  As you can see, by default this option is not enabled.

How to escape text when paste as String literal Eclipse Tips


Next time no need to extra edit any XML or HTML text before pasting as String literal in Eclipse IDE. Eclipse will do it for you automatically. Once again, if you are doing anything manually and think that it would be good Eclipse can assist on that task, look for it using google or Eclipse help. There is good chance you can discover a useful Eclipse shortcut or settings.
Other Eclipse tutorials and tips for Java programmer

How to remote debug Java program in Eclipse

Eclipse shortcut to remove all unused imports in Java

How to line comment or block comment Java code in Eclipse

Eclipse shortcut for generating System.out.println statement quickly

10 Java debugging Tips in Eclipse IDE for Java programmer

Please share with your friends if like this article

JDBC Performance Tips - 4 Tips to improve performance of Java application with database

JDBC Performance tips are collection of some tried and tested way of coding and applying process which improves performance of JDBC code. Performance of core java application or J2EE web application is very important, especially if its using database in back end which tend to slow down performance drastically. do you experience your java j2ee web application to be very slow (taking few seconds to process simple requests which involves database access, paging, sorting etc) than below tips may improve performance of your Java application. these tips are simple in nature and can be applied to other programming language application which uses database as back-end.

Improve performance Java application with database

4 JDBC Performance Tips

how to improve performance Java database application Here are four JDBC performance tips, not really super cool or something you never heard and I rather say fundamentals but in practice many programmers  just missed these, you may also called this database performance tips but I prefer to keep them as Java because I mostly used this when I access database from Java application.

JDBC Performance Tips 1: Use Cache

Find out how many database calls you are making and minimize those believe it or not if you see performance in seconds than in most cases culprit is database access code. since connecting to database requires connections to be prepared, network round trip and processing on database side, its best to avoid database call if you can work with cached value. even if your application has quite dynamic data having a short time cache can save many database round trip which can boost your java application performance by almost 20-50% based on how many calls got reduced. In order to find out database calls just put logging for each db call in DAO layer, even better if you log in and out time which gives you idea which call is taking how much time.

Java database performance tips 2: Use Database Index

Check whether your database has indexed on columns if you are reading from database and your query is taking longer than expected than first thing you should check is whether you have index on columns which you are using for search (in where clause of query). this is most common error programmers make and believe me there is huge difference than querying a database which is indexed and the one which is not. This tip can boost your performance by more than 100% but as I said its mistake now having proper indexes in your tables so don't do that in first place. Another point which is worth noting is that too many indexes slows insert and update operation so be careful with indexes and always go on suitable and practical numbers like having indexes on fields which most often used for searching like id, category, class etc.

JDBC performance tips 3: Use PreparedStatement

Use PreparedStatement or Stored Procedure for executing query Prepared Statements are much faster than normal Statement object as database can pre-compile them and also cache there query plan. so always use parametric form of Prepared Statement like "select * from table where id=?" , don't use "select * from table where id='" + id "'" which is still a prepared Statement but not parametrized. you won't get performance benefit of preparestatment by using second form. see here for more advantages of PreparedStatement in Java like prevention from SQL Injection.

Java database performance tips 4:Use Database Connection Pool
Use Connection Pool for holding Database Connections. Creating Database connections are slow process in Java and take long time. So if you are creating connection on each request than obviously your response time will be lot more. Instead if you use Connection pools with adequate number of connections based upon your traffic or number of concurrent request to make to database you can minimize this time. Even with Connection pooling few of first request may take little longer to execute till your connection gets created and cached in pool.

JDBC performance tips 5:Use JDBC Batch Update

using JDBC batch update can improve performance of Java database application significantly. you should always execute your insert and update queries on Java using batch. You can execute batch queries in Java by using either Statement or PreparedStatement. Prepared Statement is preferred because of other advantages. Use executeBatch() method to execute batch queries

JDBC performance tips 6:Disable auto commit

This is one of those JDBC performance tips which provides substantial benefit by small change. One of the better ways to improve performance of Java database application is running queries with setAutoCommit(false). By default new JDBC connection has there auto commit mode ON, which means every individual SQL Statement will be executed in its own transaction. while without auto commit you can group SQL statement into logical transaction, which can either be committed or rolled back by calling commit() or rollback(). Also its significant performance gain when you commit() explicitly. try running same query number of times with and without auto-commit and you can see how much different it make



These Java database application performance tips are very simple in nature and most of advanced Java developers already employ these while writing production code, but same time I have seen many java programmers which doesn't put so much attention until they found there java application is very slow. So geeks and expert may not get anything new but for beginners this is something worth remembering and applying. You can also use this Java performance tips as code review checklist of what not to do while writing Java applications which uses database in back-end.

That's all on how to improve performance of java programs with database. let me know if you have some other java or database tips which is helpful to boost performance of java database applications.
Java Tutorials you may like

How SubString works in Java

Difference between Comparator and Comparable in Java

How to write Thread-Safe Code in Java

Quick guide to generics wild cards in Java

Difference between JVM, JDK and JRE

15 Multi-threading Interview questions asked in Java

Why main is Static in Java

Please share with your friends if like this article

File permissions in UNIX Linux with Example >> Unix Tutorial

Whenever we execute ls command in UNIX you might have observed that it list file name with lot of details e.g.

stock_options:~/test ls -lrt
-rw-r--r-- 1 stock_options Domain Users 1.1K Jul 15 11:05 sample

If you focus on first column you will see the file permissions as "-rw-r--r--" this is made of three parts user, group and others. User part is permission relate to user logged in, group is for all the members of group and others is for all others. also each part is made of three permissions read, write and execute so "rw-" means only "read and write" permission and "r--" means read only permission. So if you look permission of example file it has read and writes access for user, read only access for groups and others. Now by using chmod command in UNIX we can change the permissions or any file or directory in UNIX or Linux. Another important point to remember is that we need execute permission in a directory to go inside a directory; you can not go into directory which has just read and write permission.

Understanding File permissions in UNIX Linux with Example


what is file permission in unix and linux with exampleFile permission in Numeric format

File permission can also be expressed in numeric format usually octal number system is used to express file permissions

   0 – no permissions
   1 – execute only
   2 – write only
   3 – write and execute
   4 – read only
   5 – read and execute
   6 – read and write
   7 – read, write and execute

Symbolic format of file permissions in UNIX

Symbolic format is another format of denoting UNIX file permissions. In symbolic format we have special notations for user, group and others as well as to denote read, write and execute permissions as shown below and by using these symbols you can set any permissions on file in Linux.

Reference       Class   Description
u       user    the owner of the file
g       group   users who are members of the file's group
o       others  users who are not the owner of the file or members of the group
a       all     all three of the above, is the same as ugo
r       read    read a file or list a directory's contents
w       write   write to a file or directory
x       execute execute a file or recurse a directory tree


Default permissions on files and directory in UNIX

Whenevera process creates a file it uses default permission 666 for file and 777 for directory. You can use "umask" command to further restrict the permissions of file or directory at creation time. umask value is used to eliminate the permissions specified by umask. for example a common umask values is "022" which makes file read and write permission for owner or group but read only for group members and other and in case of directory it makes directory searchable with execute permissions for all user, group and others because you can not go inside a directory in UNIX or Linux if you don't have execute permissions on that. Let’s see an example how we arrived to this file permissions:

Default permission of file -- 666
usmak                      -- 022
----------------------------------
Final permissions on file -- 644 (which is 110 100 100 i.e. rw- r-- r--) read and write for user and read only for group and others
Default permission of directory -- 777
umask                            -- 022
----------------------------------------
Final permission of file         -- 755 (which is 111 101 101 i.e. rwx r-x r-x) read, write and execute for user (owner) and read+execute for group members and others.

How to change file and directory permission in UNIX

You can use chmod command to change permissions of any file or directory in UNIX or Linux. Chmod command stands for change mode for example from read only mode to writable. Let’s see and example of creating a read only file and then granting it full access in UNIX or Linux.

stock_options:~/test touch stock_trading_systems
stock_options:~/test ls -lrt
-rw-r--r--  1 stock_options Domain Users    0 Nov 15 11:42 stock_trading_systems
stock_options:~/test chmod 400 stock_trading_systems
stock_options:~/test ls -lrt
-r--------  1 stock_options Domain Users    0 Nov 15 11:42 stock_trading_systems
stock_options:~/test vim stock_trading_systems
stock_options:~/test chmod 777 stock_trading_systems
stock_options:~/test ls -lrt
-rwxrwxrwx  1 stock_options Domain Users    0 Nov 15 11:42 stock_trading_systems*

You can see file permission changed to rwxrwxrwx , if you have noticed there is also a * mark at the end of file name “stock_trading_systems*” that shows that this is an executable file. To enable this option you can setup an alias “ls=ls –F” , -F displays that option.
That’s all on File permission on UNIX and Linux OS for now. Please add any important point related to file permissions which are not discussed here. In Summary having good understanding of file and directory permissions in UNIX and how to change file permissions is key for working productively in Linux.
Other UNIX Command Tutorials and Examples

Top 30 UNIX command interview Question Answers
How to update soft link in UNIX in one Step

10 example of grep command in UNIX

10 tips and tutorial on UNIX command for beginners

How to find IP Address from Hostname in Linux

How to improve speed and productivity in Unix

10 example of networking command in UNIX

How to Sort Files using Sort command in Linux
Archiving files in Unix using tar command with Example

Please share with your friends if like this article

XPath Tutorials Examples for Beginners and Java Developers

XPath Tutorials Examples for Beginners and Java Developers

XPath Tutorials for Beginners and Java Developers
This XPath Tutorial is collection of my Xpath Notes which I prepared recently when I was working on XML and XPATH. Though I was familiar with XML but not with Xpath and thought to note down bullet points about Xpath to get myself up and running. It’s not quite detailed but gives a nice overview on what is Xpath and how can you use Xpath in Java. I have not edited order of notes and presented it as it is in this XPath Tutorial. It also contains some example of xpath expression to give you an idea of how they look like but its analogous to SQL which is used to retrieve data from tables.

XPath Tutorials for Beginners

xpath tutorials for beginners example

1. When you want to extract any information from XML documents, simple way is to use XPath expression
2. XPath is used to query XML document.
3. XPath is similar to SQL, SQL is used to query relational database while XPath is used to query XML documents
4. DOM can also be used to extract information form XML document but its not as easy to write, maintain and debug as XPath expression for example for getting "all books whose author is JK Rolling" in XPath is "//book[author="JK Rolling"]/title" while if you use DOM you need to traverse the file, iterate through nodes and then find the information good 20 line of code.
5. XPath is not a full fledged language there are certain things we can not do in XPAth like we can not find all the authors for which external account database shows royalty is due.
6. Java + XPath can complement each other.
7. Java 5 has a library called javax.xml.xpath for querying XML document using XPath and this library is independent of XML Object model.
8. Xalan and Saxon are two XPath engine and they provide there own API for XPath processing.
9. Before Java 5 XPath API java API was XPAth engine dependent.
10. Different object model in XML are DOM (Document Object Model), JDOM and XOM and XPathFactory uses abstract factory design pattern to support multiple object model.
11. JAXP is the java API for xml processing which contains xml parsers and DOM is API provided by w3c.
12. For easier understanding we can correlate XPath to SQL and javax.xml.xpath to javax.sql
13. Its easy to write query in declarative language e.g. SQL and XPath then imperative language like C and Java.
14. XPath 1.0 has four basic data types "node-set", "number", "boolean" and "string".
15. Most XPath expression, especially location paths return note set.
16. Count (//book) return number of book a number
17. Count (//book) > 5 returns Boolean
18. Generally speaking, an XPath
Number maps to a java.lang.Double
String maps to a java.lang.String
Boolean maps to a java.lang.Boolean
node-set maps to an org.w3c.dom.NodeList
19. evaluate() method of XPath API has return type Object but actual type depends upon the type of XPath expression.
20. Second argument of evaluate() method take the expected return type. Corresponding java types are defined in XPathConstants class as
21. XPathConstants.NODE is a special type which only return single node, so if result of XPath query return more than one node then if this return type is specified it will return first node and if XPath query doesn't return any element than evaluate() will return null. If the requested conversion between Java and XPath can't be made, then evaluate() throws an XPathException.
23. There are some minus points as well with this API; first current implementation of this API on JDK only supports DOM, though you can get other implementation which support JDOM and XOM e.g Saxon implementation. Another drawback of this API is that it’s mostly based on
XPath 1.0, there is not much support for XPath2.0. One more disadvantage which in turn an advantage is this API is object model independent which mean most of interfaces are represented as Object and lack type-safety.
This is very raw XPath tutorial and as I said I have not edited it just presented as it is to preserve the order. I may adjust or modify this article when I get some more time. For Now that’s all on this Xpath tutorial.
Some other Tutorial you may like

How to solve OutOfMemoryError in ANT 

How to Split String in Java Example

10 Example of Enum in Java

What are inbuilt Properties in Apache ANT

Difference between String and StringBuffer in Java

How to convert String to Integer in Java

How to increase Heap Size in Maven and ANT

Please share with your friends if like this article

How Garbage Collection works in Java

How Garbage Collection works in Java



I have read many articles on Garbage Collection in Java, some of them are too complex to understand and some of them don’t contain enough information required to understand garbage collection in Java. Then I decided to write my own experience as an article or you call tutorial about How Garbage Collection works in Java or what is Garbage collection in Java in simple word which would be easy to understand and have sufficient information to understand how garbage collection works in Java.

Garbage collection in Java TutorialThis article is  in continuation of my previous articles How Classpath works in Java and How to write Equals method in java and  before moving ahead let's recall few important points about garbage collection in java:

1) objects are created on heap in Java  irrespective of there scope e.g. local or member variable. while its worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread.
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
3) Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
5) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
6) You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
7) There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space
9) J2SE 5(Java 2 Standard Edition) adds a new feature called Ergonomics goal of ergonomics is to provide good performance from the JVM with minimum of command line tuning.


When an Object becomes Eligible for Garbage Collection

An Object becomes eligible for Garbage collection or GC if its not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null. Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don't have any other live reference then both Objects A and B will be eligible for Garbage collection.
Generally an object becomes eligible for garbage collection in Java on following cases:
1) All references of that object explicitly set to null e.g. object = null
2) Object is created inside a block and reference goes out scope once control exit that block.
3) Parent object set to null, if an object holds reference of another object and when you set container object's reference null, child or contained object automatically becomes eligible for garbage collection.
4) If an object has only live references via WeakHashMap it will be eligible for garbage collection. To learn more about HashMap see here How HashMap works in Java.

Heap Generations for Garbage Collection in Java

Java objects are created in Heap and Heap is divided into three parts or generations for sake of garbage collection in Java, these are called as Young generation, Tenured or Old Generation and Perm Area of heap.
New Generation is further divided into three parts known as Eden space, Survivor 1 and Survivor 2 space. When an object first created in heap its gets created in new generation inside Eden space and after subsequent Minor Garbage collection if object survives its gets moved to survivor 1 and then Survivor 2 before Major Garbage collection moved that object to Old or tenured generation.

Permanent generation of Heap or Perm Area of Heap is somewhat special and it is used to store Meta data related to classes and method in JVM, it also hosts String pool provided by JVM as discussed in my string tutorial why String is immutable in Java. There are many opinions around whether garbage collection in Java happens in perm area of java heap or not, as per my knowledge this is something which is JVM dependent and happens at least in Sun's implementation of JVM. You can also try this by just creating millions of String and watching for Garbage collection or OutOfMemoryError.

Types of Garbage Collector in Java

Java Runtime (J2SE 5) provides various types of Garbage collection in Java which you can choose based upon your application's performance requirement. Java 5 adds three additional garbage collectors except serial garbage collector. Each is generational garbage collector which has been implemented to increase throughput of the application or to reduce garbage collection pause times.

1) Throughput Garbage Collector: This garbage collector in Java uses a parallel version of the young generation collector. It is used if the -XX:+UseParallelGC option is passed to the JVM via command line options . The tenured generation collector is same as the serial collector.

2) Concurrent low pause Collector: This Collector is used if the -Xingc or -XX:+UseConcMarkSweepGC is passed on the command line. This is also referred as Concurrent Mark Sweep Garbage collector. The concurrent collector is used to collect the tenured generation and does most of the collection concurrently with the execution of the application. The application is paused for short periods during the collection. A parallel version of the young generation copying collector is sued with the concurrent collector. Concurrent Mark Sweep Garbage collector is most widely used garbage collector in java and it uses algorithm to first mark object which needs to collected when garbage collection triggers.

3) The Incremental (Sometimes called train) low pause collector: This collector is used only if -XX:+UseTrainGC is passed on the command line. This garbage collector has not changed since the java 1.4.2 and is currently not under active development. It will not be supported in future releases so avoid using this and please see 1.4.2 GC Tuning document for information on this collector.
Important point to not is that -XX:+UseParallelGC should not be used with -XX:+UseConcMarkSweepGC. The argument passing in the J2SE platform starting with version 1.4.2 should only allow legal combination of command line options for garbage collector but earlier releases may not find or detect all illegal combination and the results for illegal combination are unpredictable. It’s not recommended to use this garbage collector in java.

JVM Parameters for garbage collection in Java

Garbage collection tuning is a long exercise and requires lot of profiling of application and patience to get it right. While working with High volume low latency Electronic trading system I have worked with some of the project where we need to increase the performance of Java application by profiling and finding what causing full GC and I found that Garbage collection tuning largely depends on application profile, what kind of object application has and what are there average lifetime etc. for example if an application has too many short lived object then making Eden space wide enough or larger will reduces number of minor collections. you can also control size of both young and Tenured generation using JVM parameters for example setting -XX:NewRatio=3 means that the ratio among the young and tenured generation is 1:3 , you got to be careful on sizing these generation. As making young generation larger will reduce size of tenured generation which will force Major collection to occur more frequently which pauses application thread during that duration results in degraded or reduced throughput. The parameters NewSize and MaxNewSize are used to specify the young generation size from below and above. Setting these equal to one another fixes the young generation. In my opinion before doing garbage collection tuning detailed understanding of garbage collection in java is must and I would recommend reading Garbage collection document provided by Sun Microsystems for detail knowledge of garbage collection in Java. Also to get a full list of JVM parameters for a particular Java Virtual machine please refer official documents on garbage collection in Java. I found this link quite helpful though http://www.oracle.com/technetwork/java/gc-tuning-5-138395.html

Full GC and Concurrent Garbage Collection in Java

Concurrent garbage collector in java uses a single garbage collector thread that runs concurrently with the application threads with the goal of completing the collection of the tenured generation before it becomes full. In normal operation, the concurrent garbage collector is able to do most of its work with the application threads still running, so only brief pauses are seen by the application threads. As a fall back, if the concurrent garbage collector is unable to finish before the tenured generation fill up, the application is paused and the collection is completed with all the application threads stopped. Such Collections with the application stopped are referred as full garbage collections or full GC and are a sign that some adjustments need to be made to the concurrent collection parameters. Always try to avoid or minimize full garbage collection or Full GC because it affects performance of Java application. When you work in finance domain for electronic trading platform and with high volume low latency systems performance of java application becomes extremely critical an you definitely like to avoid full GC during trading period.

Summary on Garbage collection in Java

1) Java Heap is divided into three generation for sake of garbage collection. These are young generation, tenured or old generation and Perm area.
2) New objects are created into young generation and subsequently moved to old generation.
3) String pool is created in Perm area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM.
4) Minor garbage collection is used to move object from Eden space to Survivor 1 and Survivor 2 space and Major collection is used to move object from young to tenured generation.
5) Whenever Major garbage collection occurs application threads stops during that period which will reduce application’s performance and throughput.
6) There are few performance improvement has been applied in garbage collection in java 6 and we usually use JRE 1.6.20 for running our application.
7) JVM command line options –Xmx and -Xms is used to setup starting and max size for Java Heap. Ideal ratio of this parameter is either 1:1 or 1:1.5 based upon my experience for example you can have either both –Xmx and –Xms as 1GB or –Xms 1.2 GB and 1.8 GB.
8) There is no manual way of doing garbage collection in Java.

Please share with your friends if like this article