Table Of ContentMastering Lambdas
This page intentionally left blank
Mastering Lambdas:
Java Programming in
a Multicore World
Maurice Naftalin
NewYork Chicago SanFrancisco
Athens London Madrid MexicoCity Milan
NewDelhi Singapore Sydney Toronto
Copyright © 2015 by Maurice Naftalin. All rights reserved. Except as permitted under the United States Copyright Act of 1976, no
part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system,
without the prior written permission of the Publisher, with the exception that the program listings may be entered, stored, and executed in
a computer system, but they may not be reproduced for publication.
ISBN: 978-0-07-182963-2
MHID: 0-07-182963-6
The material in this eBook also appears in the print version of this title: ISBN: 978-0-07-182962-5,
MHID: 0-07-182962-8.
eBook conversion by codeMantra
Version 1.0
All trademarks are trademarks of their respective owners. Rather than put a trademark symbol after every occurrence of a trademarked
name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trade-
mark. Where such designations appear in this book, they have been printed with initial caps.
McGraw-Hill Education eBooks are available at special quantity discounts to use as premiums and sales promotions or for use in corporate
training programs. To contact a representative, please visit the Contact Us page at www.mhprofessional.com.
Oracle and Java are registered trademarks of Oracle Corporation and/or its affiliates. All other trademarks are the property of their
respective owners, and McGraw-Hill Education makes no claim of ownership by the mention of products that contain these marks.
Screen displays of copyrighted Oracle software programs have been reproduced herein with the permission of Oracle Corporation and/or
its affiliates.
Information has been obtained by Publisher from sources believed to be reliable. However, because of the possibility of human or
mechanical error by our sources, Publisher, or others, Publisher does not guarantee to the accuracy, adequacy, or completeness of any
information included in this work and is not responsible for any errors or omissions or the results obtained from the use of such information.
Oracle Corporation does not make any representations or warranties as to the accuracy, adequacy, or completeness of any information
contained in this Work, and is not responsible for any errors or omissions.
TERMS OF USE
This is a copyrighted work and McGraw-Hill Education and its licensors reserve all rights in and to the work. Use of this work is subject
to these terms. Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may
not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate,
sell, publish or sublicense the work or any part of it without McGraw-Hill Education’s prior consent. You may use the work for your own
noncommercial and personal use; any other use of the work is strictly prohibited. Your right to use the work may be terminated if you fail
to comply with these terms.
THE WORK IS PROVIDED “AS IS.” McGRAW-HILL EDUCATION AND ITS LICENSORS MAKE NO GUARANTEES OR
WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM
USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK
OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. McGraw-Hill Education and
its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be
uninterrupted or error free. Neither McGraw-Hill Education nor its licensors shall be liable to you or anyone else for any inaccuracy, error
or omission, regardless of cause, in the work or for any damages resulting therefrom. McGraw-Hill Education has no responsibility for the
content of any information accessed through the work. Under no circumstances shall McGraw-Hill Education and/or its licensors be liable
for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even
if any of them has been advised of the possibility of such damages. This limitation of liability shall apply to any claim or cause whatsoever
whether such claim or cause arises in contract, tort or otherwise.
To my boys: Joe, Isaac, Daniel, and Ben
About the Author
MauriceNaftalinhasover30years’experienceinITasadeveloper,designer,archi-
tect,manager,teacher,andauthor.Naftalin,acertifiedJavaprogrammer,hasworked
ineveryreleaseofJavatodate.HisexperienceinJavaandbusinessgiveshimaunique
perspectiveonthefundamentalchangethatcomeswithintroducinglambdaexpres-
sionsinJavaSE8.Naftalinisafrequentpresenteratconferencesworldwide,includ-
ingtheannualJavaOne.HerunsapopulartutorialsiteincollaborationwithOracle’s
development team, www.lambdafaq.org, focused on the new language features in
Java8.
About the Technical Editors
StuartMarksworksontheJDKCoreLibrariesteamintheJavaPlatformGroupatOra-
cle.Heiscurrentlyworkingonlambda,streams,andcollections,aswellasimproving
testqualityandperformance.HehaspreviouslyworkedonJavaFXandJavaMEatSun
Microsystems.Hehasover20yearsofsoftwareplatformproductdevelopmentexperi-
enceintheareasofwindowsystems,interactivegraphics,andmobileandembedded
systems.Stuartholdsamaster’sdegreeinComputerScienceandabachelor’sdegree
inElectricalEngineeringfromStanfordUniversity.Heliveswithhiswifeanddaughter
inCalifornia.
Brian Goetz is one of the leading authorities on Java programming. He is the author
oftheverysuccessfulJavaConcurrencyinPractice,aswellasover75articlesonJava
development.HewasthespecificationleadforJSR-335(LambdaExpressionsforthe
JavaLanguage)andhasservedonnumerousotherJCPExpertGroups.BrianistheJava
LanguageArchitectatOracle.
Contents
Foreword ...................................................... xi
Acknowledgments ............................................... xiii
Introduction .................................................... xv
1 TakingJavatotheNextLevel .................................... 1
1.1 FromExternaltoInternalIteration............................. 2
1.1.1 InternalIteration .................................... 4
1.1.2 TheCommandPattern................................ 5
1.1.3 LambdaExpressions ................................. 7
1.2 FromCollectionstoStreams ................................. 9
1.3 FromSequentialtoParallel .................................. 12
1.4 ComposingBehaviors ...................................... 15
1.5 Conclusion .............................................. 17
2 TheBasicsofJavaLambdaExpressions............................. 19
2.1 WhatIsaLambdaExpression? ............................... 20
2.1.1 TheSyntaxofLambdas ............................... 20
2.2 Lambdasvs.AnonymousInnerClasses ......................... 21
2.2.1 NoIdentityCrisis.................................... 22
2.2.2 ScopingRulesforLambdas ............................ 22
2.3 VariableCapture.......................................... 23
2.4 FunctionalInterfaces....................................... 26
2.5 UsingLambdaExpressions .................................. 30
2.6 MethodandConstructorReferences ........................... 31
2.6.1 StaticMethodReferences ............................. 32
2.6.2 InstanceMethodReferences ........................... 33
2.6.3 ConstructorReferences ............................... 35
vii
viii MasteringLambdas
2.7 TypeChecking ........................................... 35
2.7.1 WhatExactlyIsaFunctionType? ....................... 36
2.7.2 MatchingaFunctionType............................. 36
2.8 OverloadResolution....................................... 38
2.8.1 OverloadingwithLambdaExpressions ................... 39
2.8.2 OverloadingwithMethodReferences .................... 41
2.9 Conclusion .............................................. 42
3 IntroductiontoStreamsandPipelines ............................. 43
3.1 StreamFundamentals ...................................... 44
3.1.1 Parallel-ReadyCode ................................. 47
3.1.2 PrimitiveStreams.................................... 48
3.2 AnatomyofaPipeline ..................................... 49
3.2.1 StartingPipelines.................................... 50
3.2.2 TransformingPipelines ............................... 51
3.2.3 Non-interference.................................... 60
3.2.4 EndingPipelines .................................... 62
3.3 Conclusion .............................................. 71
4 EndingStreams:CollectionandReduction .......................... 73
4.1 UsingCollectors .......................................... 76
4.1.1 Stand-alonePredefinedCollectors....................... 76
4.1.2 ComposingCollectors ................................ 80
4.1.3 ChainingPipelines .................................. 84
4.1.4 WorkedExample:MostPopularTopics ................... 86
4.2 AnatomyofaCollector..................................... 88
4.2.1 ConcurrentCollection................................ 90
4.3 WritingaCollector ........................................ 90
4.3.1 Finishers .......................................... 94
4.3.2 WorkedExample:FindingMyBooks..................... 97
4.3.3 RulesforCollectors .................................. 101
4.4 Reduction............................................... 102
4.4.1 ReductionoverPrimitives ............................. 102
4.4.2 ReductionoverReferenceStreams ...................... 104
4.4.3 ComposingCollectorswithReduction.................... 108
4.5 Conclusion .............................................. 109
5 StartingStreams:SourcesandSpliterators .......................... 111
5.1 CreatingStreams.......................................... 112
5.2 SpliteratorsandFork/Join ................................... 119
5.2.1 StreamsfromSpliterators.............................. 122
5.3 Exceptions .............................................. 123
Contents ix
5.4 WorkedExample:Recursivegrep ............................. 127
5.5 Conclusion .............................................. 136
6 StreamPerformance ........................................... 137
6.1 Microbenchmarking ....................................... 140
6.1.1 MeasuringaDynamicRuntime ......................... 140
6.1.2 TheJavaMicrobenchmarkingHarness.................... 142
6.1.3 ExperimentalMethod ................................ 143
6.2 ChoosingExecutionMode .................................. 146
6.3 StreamCharacteristics...................................... 148
6.4 Ordering................................................ 151
6.5 StatefulandStatelessOperations ............................. 153
6.6 BoxingandUnboxing...................................... 153
6.7 SpliteratorPerformance..................................... 154
6.8 CollectorPerformance ..................................... 155
6.8.1 ConcurrentMapMerge ............................... 156
6.8.2 PerformanceAnalysis:PointGrouping ................... 157
6.8.3 PerformanceAnalysis:FindingMyBooks ................. 157
6.9 Conclusion .............................................. 158
7 APIEvolutionwithDefaultMethods .............................. 159
7.1 UsingDefaultMethods..................................... 162
7.2 WhatRoleforAbstractClasses? .............................. 164
7.3 DefaultMethodSyntax ..................................... 165
7.4 DefaultMethodsandInheritance ............................. 166
7.4.1 CompatibilityProblems............................... 170
7.5 StaticMethodsinInterfaces ................................. 172
7.5.1 UsingStaticMethods................................. 173
7.6 Conclusion .............................................. 173
Conclusion .................................................. 175
Index ...................................................... 177