O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Hands-On High Performance with Spring 5

Book Description

A hands-on guide to creating, monitoring, and tuning a high performance Spring web application

About This Book
  • Understand common performance pitfalls and improve your application's performance
  • Build and deploy strategies for complex applications using the microservice architecture
  • Understand internals of JVM - the core of all Java Runtime Environments
Who This Book Is For

If you're a Spring developer who'd like to build high performance applications and have more control over your application's performance in production and development, this book is for you. Some familiarity with Java, Maven, and Eclipse is necessary.

What You Will Learn
  • Master programming best practices and performance improvement with bean wiring
  • Analyze the performance of various AOP implementations
  • Explore database interactions with Spring to optimize design and configuration
  • Solve Hibernate performance issues and traps
  • Leverage multithreading and concurrent programming to improve application performance
  • Gain a solid foundation in JVM performance tuning using various tools
  • Learn the key concepts of the microservice architecture and how to monitor them
  • Perform Spring Boot performance tuning, monitoring, and health checks
In Detail

While writing an application, performance is paramount. Performance tuning for real-world applications often involves activities geared toward detecting bottlenecks. The recent release of Spring 5.0 brings major advancements in the rich API provided by the Spring framework, which means developers need to master its tools and techniques to achieve high performance applications.

Hands-On High Performance with Spring 5 begins with the Spring framework's core features, exploring the integration of different Spring projects. It proceeds to evaluate various Spring specifications to identify those adversely affecting performance. You will learn about bean wiring configurations, aspect-oriented programming, database interaction, and Hibernate to focus on the metrics that help identify performance bottlenecks. You will also look at application monitoring, performance optimization, JVM internals, and garbage collection optimization. Lastly, the book will show you how to leverage the microservice architecture to build a high performance and resilient application.

By the end of the book, you will have gained an insight into various techniques and solutions to build and troubleshoot high performance Spring-based applications.

Style and approach

This book takes a step-by-step approach with focused examples to teach you how to increase application performance.

Downloading the example code for this book You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

Table of Contents

  1. Title Page
  2. Copyright and Credits
    1. Hands-On High Performance with Spring 5
  3. Packt Upsell
    1. Why subscribe?
    2. PacktPub.com
  4. Contributors
    1. About the authors
    2. About the reviewer
    3. Packt is searching for authors like you
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Download the color images
      3. Conventions used
    4. Get in touch
      1. Reviews
  6. Exploring Spring Concepts
    1. Introducing the Spring Framework
      1. Problems with EJB
      2. Simplifying implementation using POJO
      3. Benefits of the Spring Framework
        1. No need to reinvent the wheel
        2. Ease of unit testing
        3. Reduction in implementing code
        4. Inversion of control and API
        5. Consistency in transaction management
        6. Modular architecture
        7. Up to date with time
    2. Understanding Spring modules
      1. Core Container
      2. Crosscutting concerns
      3. Data Access/Integration
      4. Web
    3. Spring projects
      1. Spring Boot
      2. Spring Data
      3. Spring Batch
      4. Spring Cloud
      5. Spring Security
      6. Spring HATEOAS
    4. Spring's IoC container
      1. What are Spring beans?
      2. Instantiating a Spring container
        1. BeanFactory
        2. ApplicationContext
      3. Spring bean life cycle
    5. New features in the Spring Framework 5.0
      1. Baseline upgrades
      2. Reactive programming support
      3. Core features upgrades
      4. Spring Web MVC upgrades
      5. Spring's new functional web framework – WebFlux
      6. Modularity support
      7. Kotlin language support
      8. Improved testing support
      9. Dropped or deprecated features
    6. Summary
  7. Spring Best Practices and Bean Wiring Configurations
    1. Dependency injection configurations
      1. Types of DI patterns
        1. Constructor-based DI
          1. Advantages of the constructor-based DI
          2. Disadvantages of the constructor-based DI
        2. Setter-based DI
          1. Advantages of the setter-based DI
          2. Disadvantages of the setter-based DI
        3. Field-based DI
        4. Constructor versus setter injection
      2. Configuring the DI with Spring
        1. XML-based configuration
        2. Java-based configuration
        3. Annotation-based configuration
          1. The @Autowired annotation
          2. @Autowired with required = false
          3. The @Primary annotation
          4. The @Qualifier annotation
          5. Automatic bean detection with stereotype annotations
          6. The @ComponentScan annotation
          7. The @Lazy annotation
      3. Spring bean scopes
    2. Performance assessment with different configurations
      1. Lazy loading versus preloading
      2. Singleton versus prototype bean
      3. Spring bean configuration best practices
    3. DI pitfalls
      1. First pitfall
      2. Second pitfall (with AOP)
    4. Summary
  8. Tuning Aspect-Oriented Programming
    1. AOP concepts
      1. Limitations of OOP
      2. Code tangling
      3. Code scattering
      4. AOP – problem solver
      5. Spring AOP terminology and concepts
        1. Defining pointcuts
        2. Types of advice
        3. Aspect instantiation models
    2. AOP proxies
      1. JDK dynamic proxies and CGLIB proxies
      2. ProxyFactoryBean
        1. ProxyFactoryBean in action
      3. Performance JDK dynamic proxy versus CGLIB proxy
      4. Caching
    3. AOP method profiling
      1. PerformanceMonitorInterceptor 
      2. Custom monitoring interceptor
    4. Spring AOP versus AspectJ
      1. What is AspectJ?
      2. Differences between Spring AOP and AspectJ
        1. Capabilities and goals
        2. Weaving
        3. Join points
        4. Simplicity
        5. Performance
      3. AspectJ with Spring
    5. AOP best programming practices
      1. Pointcut expressions
      2. Advice ordering
      3. Best practices of AOP proxies
      4. Caching
    6. Summary
  9. Spring MVC Optimization
    1. Spring MVC configuration
      1. Spring MVC architecture
      2. XML-based configuration
        1. Configuring front controller
        2. Creating a Spring application context
        3. Configuring ViewResolver
      3. Java-based configuration
        1. Configuring front controller
        2. Creating a Spring application context and configuring a ViewResolver
      4. Creating a controller
      5. Creating a view
    2. Spring asynchronous processing, @Async annotation
      1. @Async annotation modes
        1. Fire and forget mode
        2. Result retrieval mode
      2. Limitations of @Async annotation
      3. Thread pool executor
    3. CompletableFuture with Spring Async
      1. runAsync() – running a task asynchronously
      2. supplyAsync() – running a task asynchronously, with a return value
      3. Attaching a callback to the CompletableFuture
    4. Spring Security configuration
      1. Configuring Spring Security dependencies
      2. Configuring a security filter for incoming requests
      3. Configuring Spring Security
      4. Adding a controller
    5. Authentication cache
      1. Implementing the caching configuration class
      2. Providing UserCache to AuthenticationProvider
      3. Providing AuthenticationProvider to AuthenticationManagerBuilder
    6. Fast and stateless API authentication with Spring Security
      1. API authentication with the JSESSIONID cookie
      2. API authentication without the JSESSIONID cookie
    7. Monitoring and managing Tomcat with JMX
      1. Connecting JMX to monitor Tomcat
      2. Creating an MBean
      3. Exporting an MBean in a Spring context
    8. Spring MVC performance improvements
      1. High performance using connection pooling
      2. Hibernate improvements
      3. Testing improvements
      4. Proper server maintenance
      5. Using the authentication cache with Spring Security
      6. Implementing Executor service framework
    9. Summary
  10. Understanding Spring Database Interactions
    1. Spring JDBC configuration
      1. Problems with core JDBC
      2. Solving problems with Spring JDBC
      3. Spring JDBC dependencies
      4. Spring JDBC example
    2. Database design for optimal performance
      1. Table design
        1. Vertical partitioning of a table
      2. Use indexing
      3. Using the correct data type
      4. Defining column constraints
      5. Using stored procedures
    3. Transaction management
      1. Choosing a transaction manager in Spring
      2. Declarative ACID using @Transactional
    4. Optimal isolation levels
      1. Read uncommitted
      2. Read committed
      3. Repeatable read
      4. Serializable
    5. Optimal fetch size
    6. Optimal connection pooling configuration
      1. Sizing the connection pool
      2. Validate connections
      3. Connection leaks
      4. Tomcat JDBC connection pool versus HikariCP
        1. Reliability
        2. Performance
        3. Features
        4. Ease of use
    7. Database interaction best practices
      1. Using Statement versus PreparedStatement versus CallableStatement
      2. Using Batch instead of PreparedStatement
      3. Minimizing the use of database metadata methods
      4. Using get methods effectively
      5. When to avoid connection pooling
      6. Choose commit mode carefully
    8. Summary
  11. Hibernate Performance Tuning and Caching
    1. Introduction to Spring Hibernate and Spring Data
      1. Spring Hibernate
      2. Spring Data
    2. Spring Hibernate configuration
      1. Spring with JPA using Hibernate
      2. Spring Data configuration
    3. Common Hibernate traps
      1. Hibernate n + 1 problem
      2. The open session in view anti-pattern
      3. Unknown Id.generator exception
    4. Hibernate performance tuning
      1. Approaches to avoid the n + 1 problem
        1. Fetch join using JPQL
        2. Join fetch in Criteria API
        3. Named entity graph
        4. Dynamic entity graph
      2. Finding performance issues with Hibernate statistics
      3. Using query-specific fetching
      4. Caching and its best practices
        1. First level cache
        2. Second level cache
        3. Query cache
      5. Performing updates and deletes in bulk
    5. Hibernate programming practices
      1. Caching
      2. Miscellaneous
    6. Summary
  12. Optimizing Spring Messaging
    1. What is messaging?
    2. What is AMQP?
      1. Problems with the JMS API
      2. Why do we need AMQP?
      3. Differences between AMQP and the JMS API
        1. Platform compatibility
        2. Messaging models
        3. Message data type
        4. Message structure
        5. Message routing
        6. Workflow strategy
      4. What are exchanges, queues, and bindings?
        1. Exchange
        2. Queue
        3. Binding
    3. Introducing RabbitMQ
      1. Setting up the RabbitMQ server
    4. Spring messaging configuration
      1. Configuring a Maven dependency for RabbitMQ
      2. Configuring RabbitMQ
        1. Configuring ConnectionFactory
        2. Configuring a queue
        3. Configuring an exchange
        4. Configuring a binding
        5. Configuring RabbitAdmin
        6. Configuring a message converter
        7. Creating a RabbitTemplate
        8. Configuring a listener container
      3. Creating a message receiver
      4. Creating a message producer
    5. Maximizing throughput with RabbitMQ
      1. Performance and scalability with RabbitMQ
    6. Summary
  13. Multithreading and Concurrent Programming
    1. Java classical threads
      1. Creating threads
      2. Thread life cycle and states
      3. More advanced thread tasks
      4. Synchronizing threads
      5. Issues with multithreading
    2. The java.util.concurrent package
      1. Executors
      2. ThreadFactory
      3. Synchronizers
      4. Concurrent collection classes
      5. Lock
      6. Callable and Future
      7. Atomic variables
    3. Using thread pools for asynchronous processing
    4. Spring task execution and scheduling
      1. TaskExecutor
      2. TaskScheduler
    5. Spring Async
      1. The @EnableAsync annotation
      2. The @Async annotation
      3. @Async with CompletableFuture
    6. Spring and threads – transactions
    7. Java threads best programming practices
    8. Summary
  14. Profiling and Logging
    1. Performance profiling
      1. Application performance
    2. Application logging and monitoring
      1. Application logging
      2. Logging best practices
      3. Logging tools
        1. Java standard logging
        2. Apache Log4j 2
      4. Application monitoring
        1. Stagemonitor
        2. Pinpoint
        3. MoSKito
        4. Glowroot
        5. New Relic
    3. Profiling tools
      1. VisualVM
      2. JConsole
    4. Summary
  15. Application Performance Optimization
    1. Performance issue symptoms
      1. Timeouts
      2. Running out of worker threads
      3. Threads waiting on class loaders
      4. Time spent on class-loading activities
      5. Class loader trying to load non-existent classes
    2. Performance tuning life cycle
      1. Connection pooling
      2. Hibernate
        1. Transaction
        2. Periodical clearing of Hibernate sessions
        3. Lazy initialization
        4. Constructor-based HQLs
        5. Entity and query caching
        6. Native queries
        7. Primary key generation
      3. Database
        1. Indexing
      4. Spring Security
        1. Authentication cache
        2. LDAP custom authorities
        3. Native LDAP
      5. Multithreading
    3. Performance tuning patterns and anti-patterns
      1. Anti-patterns
        1. Architectural anti-patterns
        2. Implementing anti-patterns
    4. The iterative performance-tuning process
    5. Spring support of JMX
      1. Managed beans
    6. Summary
  16. Inside JVM
    1. Understanding JVM internals
      1. Class loader subsystem
      2. Memory areas
      3. Execution engine
    2. Understanding memory leak
      1. Memory leak in Java
      2. Common reasons for memory leaks
    3. Common pitfalls
      1. Number of garbage collectors
      2. Wrong garbage collector
      3. Parallel / Concurrent keywords
      4. G1 is a problem solver
      5. Average transaction time
      6. Reducing new object allocation rates improves GC behavior
      7. GC logs cause overhead
    4. GC
      1. How GC works
      2. GC roots
    5. GC methods and policies
      1. Serial collector
      2. Parallel/Throughput collector
      3. CMS garbage collector
      4. G1 collector
    6. Heap memory
    7. JVM flags
      1. -Xms and -Xmx
      2. -XX:NewSize and -XX:MaxNewSize
      3. -XX:NewRatio
      4. -XX:SurvivorRatio
      5. -XX:InitialTenuringThreshold, -XX:MaxTenuringThreshold, and -XX:TargetSurvivorRatio
      6. -XX:CMSInitiatingOccupancyFraction
      7. -XX:+PrintGCDetails, -XX:+PrintGCDateStamps, and -XX:+PrintTenuringDistribution
    8. Tools to analyze GC logs
      1. GCeasy
        1. Tips on JVM tuning
        2. JVM Heap Size
        3. Key Performance Indicators
        4. GC Statistics
        5. GC Causes
    9. Summary
  17. Spring Boot Microservice Performance Tuning
    1. Spring Boot configuration
      1. What is Spring Boot?
      2. Spring Initializr
      3. Starters with Maven
      4. Creating your first Spring Boot application
    2. Metrics with Spring Boot Actuator
      1. What is Spring Actuator?
      2. Enabling Spring Boot Actuator
      3. Enabling endpoints
    3. Health checks
    4. Microservices using Spring Boot
      1. First microservice with Spring Boot
      2. Loading sample data into the database
        1. The JPA way of initial data loading
        2. The ApplicationRunner way of initial data loading
      3. Microservice client
    5. Microservices with Spring Cloud
    6. Spring microservice configuration example
    7. Monitoring microservices with Spring Boot admin
    8. Spring Boot performance tuning
      1. Undertow as an embedded server
      2. Overhead with the @SpringBootApplication annotation
    9. Summary
  18. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think