Http://java.dzone.com/articles/performance-tuning
For most typical spring/hibernate enterprise applications, the application performance depends almost entirely on the perf Ormance of it ' s persistence layer.
This post would go over what to confirm that we were in presence of a ' database-bound ' application, and then walk through 7 f requently used ' Quick-win ' tips that can help improve application performance.
How to confirm a application is ' Database-bound '
To confirm the application is ' Database-bound ', start by doing a typical run in some development environment, using Vi SUALVM for monitoring. VisualVM is a Java profiler shipped with the JDK and launchable via the command line by calling jvisualvm .
After launching Visual VM, try the following steps:
- Double click on your running application
- Select Sampler
- Click on
Settings checkbox
- Choose
Profile only packages , and type in the following packages:
your.application.packages.*
org.hibernate.*
org.springframework.*
your.database.driver.package, for exampleoracle.*
- Click
Sample CPU
The CPU profiling of a typical ' database-bound ' application should look something like this:
We can see that the client Java process spends of it's time waiting for the 56% database to return results over the net Work.
This was a good sign, the queries on the database was what ' s keeping the application slow. The in 32.7% Hibernate reflection calls are normal and nothing much can be do about it.
First step for tuning-obtaining a baseline run
The first step to do tuning are to define a baseline run for the program. We need to identify a set of functionally valid input data This makes the program go through a typical execution similar T o the production run.
The main difference is and the baseline run should run in a much shorter period of time, as a guideline a execution time of around 5 to ten minutes is a good target.
What makes a good baseline?
A good baseline should has the following characteristics:
- It ' s functionally correct
- The input data is similar to production in it s variety
- It completes in a short amount of time
- Optimizations in the baseline run can is extrapolated to a full run
Getting a good baseline is solving half of the problem.
What is makes a bad baseline?
For example, in a batch run for processing call data records in a telecommunications system, taking the first Recor DS could be the wrong approach.
The reason being, the first might be mostly voice calls, but the unknown performance problem are in the processing O F SMS traffic. Taking the first records of a large run would leads us to a bad baseline, from which wrong conclusions would is taken.
Collecting SQL logs and query timings
The SQL queries executed with their execution time can is collected using for example LOG4JDBC. See the This blog post for what to collect SQL queries using log4jdbc-spring/hibernate improved SQL logging with LOG4JDBC.
The query execution time is measured from the Java client side, and it includes the network round-trip to the database. The SQL query logs look like this:
1.16 avr. 2014 11:13:48 | SQL_QUERY /* insert your.package.YourEntity */insert into YOUR_TABLE (...) values (...) {executed in 13 msec}
The prepared statements themselves is also a good source of information-they allow to easily identify frequent query types. They can logged by following the this blog post-why and where are Hibernate doing this SQL query?
What metrics can is extracted from SQL logs
The SQL logs can give the answer these questions:
- What is slowest queries being executed?
- What is the most frequent queries?
- What is the amount of time spent generating primary keys?
- Is there some data, could benefit from caching?
How to parse the SQL logs
Probably the only viable option for large log volumes are to use command line tools. This approach has the advantage of being very flexible.
At the expense of writing a small script or command, we can extract mostly any metric needed. Any command line tool would work as long as a comfortable with it.
If you is used to the Unix command line, Bash might is a good option. Bash can is used also in Windows workstations, using for example Cygwin, or Git that includes a bash command line.
Frequently applied Quick-wins
Quick-wins bellow identify common performance problems in spring/hibernate applications, and their corresponding solut Ions.
Quick-win TIP 1-reduce primary key generation overhead
In processes that is ' insert-intensive ', the choice of a primary key generation strategy can matter a lot. One common-Generate ID ' is-to-use database sequences, usually-one per table to avoid contention between-on Different tables.
The problem is so if records is inserted and we want to avoid that network round-trips be made to the database in O Rder to obtain IDs ' s, leaving the Java process hanging most of the time.
How does Hibernate usually handle this?
Hibernate provides new optimized ID generators that avoid this problem. Namely for sequences, a- HiLo ID generator is used by default. This was how the HiLo sequence generator it works:
- Call a sequence once and get + (the high value)
- Calculate ID ' s like this:
- 1000 * 50 + 0 = 50000
- 1000 * 50 + 1 = 50001
- ...
- + * + = 50049, low value (reached)
- Call sequence for new high value 1001 ... etc ...
So from a single sequence call, the keys where generated, reducing the overhead caused my inumerous network round-trips.
These new optimized key generators is on by default in Hibernate 4, and can even is turned off if needed by setting hibernate.id.new_generator_mappings to False.
Why can primary key generation still be a problem?
The problem is, if you declared the key generation strategy AUTO as, the optimized generators isstill off, and Your application would end up with a huge amount of sequence calls.
In order to make sure the new optimized generators is on, make sure to use the SEQUENCE strategy instead of AUTO :
1.@Id2.@GeneratedValue(strategy = GenerationType.SEQUENCE, generator ="your_key_generator")3.private Long id;
With a improvement in the range of 10%-20% can is measured in ' insert-intensive ' applications, with BA Sically No code changes.
Quick-win Tip 2-use JDBC Batch Inserts/updates
For batch programs, JDBC drivers usually provide a optimization for reducing network round-trips named ' JDBC Batch Insert S/updates '. When these is used, inserts/updates is queued at the driver level before being to the database.
When a threshold was reached, then the whole batch of queued statements was sent to the database in one go. This prevents the driver from sending the statements one by one, which would waist multiple network round-trips.
The the Entity Manager factory configuration needed to active batch inserts/updates:
View Source print?1.<prop key="hibernate.jdbc.batch_size">100</prop>2.<prop key="hibernate.order_inserts">true</prop>3.<prop key="hibernate.order_updates">true</prop>
Setting only the JDBC batch size won ' t work. This is because the JDBC driver would batch the inserts only if receiving insert/updates for the exact same table.
If an inserts to a new table are received, then the JDBC driver would first flush the batched statements on the previous tabl E, before starting to batch statements on the new table.
A Similar functionality is implicitly used if using Spring Batch. This optimization can easily buy 30% 40% "Insert intensive ' programs, without changing a single line of code.
Quick-win Tip 3-periodically Flush and clear the Hibernate session
When adding/modifying data on the database, Hibernate keeps in the session a version of the entities already persisted, Ju St in case they was modified again before the session is closed.
But many times we can safely discard entities once the corresponding inserts where do in the database. This releases memory in the Java client process, preventing performance problems caused by long running Hibernate sessions .
Such long-running Sessions should be avoided as much as possible, but if by some reason they was needed, this is How to contain memory consumption:
1.entityManager.flush();2.entityManager.clear();
The'll trigger the inserts from new entities to being sent to the flush database. The clear releases the new entities from the session.
Quick-win Tip 4-reduce Hibernate dirty-checking Overhead
Hibernate uses internally a mechanism to keep track of modified entities called dirty-checking. This mechanism isn't based on the Equals and Hashcode methods of the entity classes.
Hibernate does it ' s most to keep the performance cost of dirty-checking to a minimum, and to dirty-check if it need s to, but the mechanism does had a cost, which was more noticeable in tables with a large number of columns.
Before applying any optimization, the most important are to measure the cost of dirty-checking using VisualVM.
How to avoid dirty-checking?
In Spring business methods that we know is read-only, dirty-checking can be turned off like this:
1.@Transactional(readOnly=true)2.public void someBusinessMethod() {3.....4.}
An alternative to avoid dirty-checking are to use the Hibernate stateless Session, which are detailed in thedocumentation.
Quick-win Tip 5-search for ' bad ' query plans
Check the queries in the slowest queries list to see if they has good query plans. The most usual ' bad ' query plans is:
-
Full table Scans:they happen when the table was being fully scanned due to usually a missing index or outdated table Stati Stics.
-
Full Cartesian joins:this means, the full Cartesian product of several tables are being computed. Check for missing join conditions, or if the can is avoided by splitting a step into several.
Quick-win Tip 6-check for wrong commit intervals
If you is doing batch processing, the commit interval can make a large difference in the performance results, as in Faster.
Confirm that the commit interval are the one expected (usually around 100-1000 for Spring Batch jobs). It happens often that this parameter was not correctly configured.
Quick-win Tip 7-use The second-level and query caches
If some data is identified as being eligible for caching and then has a look in this blog post for how to setup the Hibernat E Caching:pitfalls of the Hibernate second-level/query Caches
Conclusions
To solve application performance problems, the most important action to take are to collect some metrics What's the current bottleneck is.
Without some metrics it is often does possible to guess in useful time what's the correct problem cause is.
Also, many but not all of the the typical performance pitfalls of a ' database-driven ' application can is avoided in the first Place by using the Spring Batch framework.
Published at Dzone with permission of Aleksey Novik, author and Dzone MVB. (source)
(Note:opinions expressed in this article and its replies is the opinions of their respective a Uthors and not those of Dzone, Inc.)