Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

Clojure High Performance Programming - Second Edition
Clojure High Performance Programming - Second Edition
Clojure High Performance Programming - Second Edition
Ebook437 pages3 hours

Clojure High Performance Programming - Second Edition

Rating: 0 out of 5 stars

()

Read preview

About this ebook

This book is intended for intermediate Clojure developers who are looking to get a good grip on achieving optimum performance. Having a basic knowledge of Java would be helpful.
LanguageEnglish
Release dateSep 29, 2015
ISBN9781785287671
Clojure High Performance Programming - Second Edition

Related to Clojure High Performance Programming - Second Edition

Related ebooks

Programming For You

View More

Related articles

Reviews for Clojure High Performance Programming - Second Edition

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Clojure High Performance Programming - Second Edition - Kumar Shantanu

    Table of Contents

    Clojure High Performance Programming Second Edition

    Credits

    About the Author

    About the Reviewers

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    Why subscribe?

    Free access for Packt account holders

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Errata

    Piracy

    eBooks, discount offers, and more

    Questions

    1. Performance by Design

    Use case classification

    The user-facing software

    Computational and data-processing tasks

    A CPU bound computation

    A memory bound task

    A cache bound task

    An input/output bound task

    Online transaction processing

    Online analytical processing

    Batch processing

    A structured approach to the performance

    The performance vocabulary

    Latency

    Throughput

    Bandwidth

    Baseline and benchmark

    Profiling

    Performance optimization

    Concurrency and parallelism

    Resource utilization

    Workload

    The latency numbers that every programmer should know

    Summary

    2. Clojure Abstractions

    Non-numeric scalars and interning

    Identity, value, and epochal time model

    Variables and mutation

    Collection types

    Persistent data structures

    Constructing lesser-used data structures

    Complexity guarantee

    O(<7) implies near constant time

    The concatenation of persistent data structures

    Sequences and laziness

    Laziness

    Laziness in data structure operations

    Constructing lazy sequences

    Custom chunking

    Macros and closures

    Transducers

    Performance characteristics

    Transients

    Fast repetition

    Performance miscellanea

    Disabling assertions in production

    Destructuring

    Recursion and tail-call optimization (TCO)

    Premature end of iteration

    Multimethods versus protocols

    Inlining

    Summary

    3. Leaning on Java

    Inspecting the equivalent Java source for Clojure code

    Creating a new project

    Compiling the Clojure sources into Java bytecode

    Decompiling the .class files into Java source

    Compiling the Clojure source without locals clearing

    Numerics, boxing, and primitives

    Arrays

    Reflection and type hints

    An array of primitives

    Primitives

    Macros and metadata

    String concatenation

    Miscellaneous

    Using array/numeric libraries for efficiency

    HipHip

    primitive-math

    Detecting boxed math

    Resorting to Java and native code

    Proteus – mutable locals in Clojure

    Summary

    4. Host Performance

    The hardware

    Processors

    Branch prediction

    Instruction scheduling

    Threads and cores

    Memory systems

    Cache

    Interconnect

    Storage and networking

    The Java Virtual Machine

    The just-in-time compiler

    Memory organization

    HotSpot heap and garbage collection

    Measuring memory (heap/stack) usage

    Determining program workload type

    Tackling memory inefficiency

    Measuring latency with Criterium

    Criterium and Leiningen

    Summary

    5. Concurrency

    Low-level concurrency

    Hardware memory barrier (fence) instructions

    Java support and the Clojure equivalent

    Atomic updates and state

    Atomic updates in Java

    Clojure's support for atomic updates

    Faster writes with atom striping

    Asynchronous agents and state

    Asynchrony, queueing, and error handling

    Why you should use agents

    Nesting

    Coordinated transactional ref and state

    Ref characteristics

    Ref history and in-transaction deref operations

    Transaction retries and barging

    Upping transaction consistency with ensure

    Lesser transaction retries with commutative operations

    Agents can participate in transactions

    Nested transactions

    Performance considerations

    Dynamic var binding and state

    Validating and watching the reference types

    Java concurrent data structures

    Concurrent maps

    Concurrent queues

    Clojure support for concurrent queues

    Concurrency with threads

    JVM support for threads

    Thread pools in the JVM

    Clojure concurrency support

    Future

    Promise

    Clojure parallelization and the JVM

    Moore's law

    Amdahl's law

    Universal Scalability Law

    Clojure support for parallelization

    pmap

    pcalls

    pvalues

    Java 7's fork/join framework

    Parallelism with reducers

    Reducible, reducer function, reduction transformation

    Realizing reducible collections

    Foldable collections and parallelism

    Summary

    6. Measuring Performance

    Performance measurement and statistics

    A tiny statistics terminology primer

    Median, first quartile, third quartile

    Percentile

    Variance and standard deviation

    Understanding Criterium output

    Guided performance objectives

    Performance testing

    The test environment

    What to test

    Measuring latency

    Comparative latency measurement

    Latency measurement under concurrency

    Measuring throughput

    Average throughput test

    The load, stress, and endurance tests

    Performance monitoring

    Monitoring through logs

    Ring (web) monitoring

    Introspection

    JVM instrumentation via JMX

    Profiling

    OS and CPU/cache-level profiling

    I/O profiling

    Summary

    7. Performance Optimization

    Project setup

    Software versions

    Leiningen project.clj configuration

    Enable reflection warning

    Enable optimized JVM options when benchmarking

    Distinguish between initialization and runtime

    Identifying performance bottlenecks

    Latency bottlenecks in Clojure code

    Measure only when it is hot

    Garbage collection bottlenecks

    Threads waiting at GC safepoint

    Using jstat to probe GC details

    Inspecting generated bytecode for Clojure source

    Throughput bottlenecks

    Profiling code with VisualVM

    The Monitor tab

    The Threads tab

    The Sampler tab

    Setting the thread name

    The Profiler tab

    The Visual GC tab

    The Alternate profilers

    Performance tuning

    Tuning Clojure code

    CPU/cache bound

    Memory bound

    Multi-threaded

    I/O bound

    JVM tuning

    Back pressure

    Summary

    8. Application Performance

    Choosing libraries

    Making a choice via benchmarks

    Web servers

    Web routing libraries

    Data serialization

    JSON serialization

    JDBC

    Logging

    Why SLF4J/LogBack?

    The setup

    Dependencies

    The logback configuration file

    Optimization

    Data sizing

    Reduced serialization

    Chunking to reduce memory pressure

    Sizing for file/network operations

    Sizing for JDBC query results

    Resource pooling

    JDBC resource pooling

    I/O batching and throttling

    JDBC batch operations

    Batch support at API level

    Throttling requests to services

    Precomputing and caching

    Concurrent pipelines

    Distributed pipelines

    Applying back pressure

    Thread pool queues

    Servlet containers such as Tomcat and Jetty

    HTTP Kit

    Aleph

    Performance and queueing theory

    Little's law

    Performance tuning with respect to Little's law

    Summary

    Index

    Clojure High Performance Programming Second Edition


    Clojure High Performance Programming Second Edition

    Copyright © 2015 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: November 2013

    Second edition: September 2015

    Production reference: 1230915

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78528-364-2

    www.packtpub.com

    Credits

    Author

    Shantanu Kumar

    Reviewers

    Eduard Bondarenko

    Matjaz Gregoric

    Commissioning Editor

    Nadeem Bagban

    Acquisition Editor

    Larissa Pinto

    Content Development Editor

    Divij Kotian

    Technical Editor

    Anushree Arun Tendulkar

    Copy Editor

    Yesha Gangani

    Project Coordinator

    Nikhil Nair

    Proofreader

    Safis Editing

    Indexer

    Tejal Soni

    Graphics

    Abhinash Sahu

    Production Coordinator

    Manu Joseph

    Cover Work

    Manu Joseph

    About the Author

    Shantanu Kumar is a software developer living in Bengaluru, India. He works with Concur Technologies as a principal engineer, building a next-generation stack in Clojure. He started learning computer programming when he was at school, and has dabbled in several programming languages and software technologies. Having used Java for a long time, he discovered Clojure in early 2009 and has been a fan of it ever since.

    When not busy with programming or reading up on technical stuff, he enjoys reading non-fiction and cycling around Bengaluru. Shantanu is an active participant in The Bangalore Clojure Users Group, and contributes to several open source Clojure projects on GitHub. He is also the author of the first edition of the book Clojure High Performance Programming, Packt Publishing.

    I am grateful to my colleagues, Saju Pillai and Vijay Mathew, at Concur India for imparting marathon performance analysis/tuning sessions. I appreciate the input received from Andy Fingerhut and Zach Tellman on certain topics during the course of writing the second edition of the book. I also want to thank the technical reviewers and the team at Packt for their valuable input and support.

    Writing this book has been an arduous task. I want to thank my family for putting up with me while I was immersed in this book for far too many days and weekends. If not for their support, I would not have been able to do justice to the book.

    About the Reviewers

    Eduard Bondarenko is a software developer living in Kiev, Ukraine. He started programming using Basic on ZXSpectrum a long time ago. Later, he worked professionally in the web development domain.

    Eduard used Ruby on Rails for many years. Having used Ruby for a long time, he discovered Clojure in early 2009 and liked the language. Besides Ruby and Clojure, he is also interested in Erlang, Scala languages, machine learning, and logic programming.

    Matjaz Gregoric is a software developer living in Ljubljana, Slovenia, with his wife and two children. He has a BS degree in physics, and has been developing software professionally since 2007.

    During his career, Matjaz worked on various projects where he was able to get familiar with different technologies and programming languages. In 2010, he got familiar with Clojure and immediately fell in love with it. He is currently working on scalable distributed systems and complex web UIs.

    www.PacktPub.com

    Support files, eBooks, discount offers, and more

    For support files and downloads related to your book, please visit www.PacktPub.com.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    .

    https://www2.packtpub.com/books/subscription/packtlib

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Free access for Packt account holders

    If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

    Preface

    Since the first edition of this book was published in November 2013, Clojure has seen a much wider adoption and has witnessed many success stories. The newer versions of Clojure fortify its performance story while staying close to its roots—simplicity and pragmatism. This edition significantly updates the book for Clojure 1.7, and adds a new chapter on the performance measurement.

    The Java Virtual Machine plays a huge role in the performance of the Clojure programs. This edition of the book increases the focus on the JVM tools for performance management, and it explores how to use those. This book is updated to use Java 8, though it also highlights the places where features from Java 7 or 8 have been used.

    This book is updated mainly to be more of practical use to the readers. I hope that this edition will better equip the readers with performance measurement and profiling tools and with the know-how of analyzing and tuning the performance characteristics of Clojure code.

    What this book covers

    Chapter 1, Performance by Design, classifies the various use cases with respect to performance, and analyzes how to interpret their performance aspects and needs.

    Chapter 2, Clojure Abstractions, is a guided tour of various Clojure data structures, abstractions (persistent data structures, vars, macros, transducers, and so on), and their performance characteristics.

    Chapter 3, Leaning on Java, discusses how to enhance performance by using Java interoperability and features from Clojure.

    Chapter 4, Host Performance, discusses how the host stack impacts performance. Being a hosted language, Clojure has its performance directly related to the host.

    Chapter 5, Concurrency, is an advanced chapter that discusses the concurrency and parallelism features in Clojure and JVM. Concurrency is an increasingly significant way to derive performance.

    Chapter 6, Measuring Performance, covers various aspects of performance benchmarks and measuring other factors.

    Chapter 7, Performance Optimization, discusses systematic steps that need to be taken in order to identify that the performance bottlenecks obtain good performance.

    Chapter 8, Application Performance, discusses building applications for performance. This involves dealing with external subsystems and factors that impact the overall performance.

    What you need for this book

    You should acquire Java Development Kit version 8 or higher for your operating system to work through all the examples. This book discusses the Oracle HotSpot JVM, so you may want to get Oracle JDK or OpenJDK (or Zulu) if possible. You should also get the latest Leiningen version (2.5.2 as of the time of writing) from http://leiningen.org/, and JD-GUI from http://jd.benow.ca/.

    Who this book is for

    This book is for intermediate Clojure programmers who are interested in learning how to write high-performance code. If you are an absolute beginner in Clojure, you should learn the basics of the language first, and then come back to this book. You need not be well-versed in performance engineering or Java. However, some prior knowledge of Java would make it much easier to understand the Java-related chapters.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Note that identical? in Clojure is the same as == in Java.

    A block of code is set as follows:

    user=> (identical? foo foo)  ; literals are automatically interned

    true

    user=> (identical? (String. foo) (String. foo))  ; created string is not interned

    false

    New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: Clicking the Next button moves you to the next screen.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

    To send us general feedback, simply e-mail <feedback@packtpub.com>, and mention the book's title in the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.

    We appreciate your help in protecting our authors and our ability to bring you valuable content.

    eBooks, discount offers, and more

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt

    Enjoying the preview?
    Page 1 of 1