The
Well-Grounded
Java
Developer
Vital
techniques
ofJava
7
andPolyglot Programming
BENJAMIN
J.
EVANSMARTIJN
VERBURGII
MANNING Shelter Islandcontents
foreword xvii
preface xix
acknowledgments xxi
aboutthisbook xxiv about the authors xxix about thecoverillustration xxx
Part 1
Developing
withJava
7
1
Introducingjava
7 31.1 The
language
and theplatform
41.2 Small is
beautiful—Project
Coin 51.3 The
changes
in ProjectCoin 9Stringsin switch 9 Enhancedsyntaxfor
numeric literals 10 Improved exception handling 12 Try-with-^esources(TWR) 13 Diamondsyntax 16
Simplifiedvarargs methodinvocation 17
1.4
Summary
19New
I/O
202.1
Java
I/O—ahistory 22Java1.0to1.3 22 • Java1.4 andNIO 23
IntroducingNIO.2 24
CONTENTS
2.2 Path—a foundation offile-basedI/O 24
CreatingaPath 27 * Retrieving
information
fromaPath 27Removingredundancies 28 * ConvertingPaths 29
NIO. 2 Path andfava'sexistingFileclass 30
2.3
Dealing
with directories anddirectory
trees 30Findingfilesinadirectory 30 * Walkingthedirectorytree 31
2.4
Filesystem
I/Owith NIO.2 33Creatinganddeletingfiles 34 Copyingandmovingfiles 35 File attributes 36 * Readingandwritingdataquickly 40 Filechangenotification 41 SeekableByteChannel 42
2.5
Asynchronous
I/O operations 43Futurestyle 44 * Callbackstyle 46
2.6
Tidying
up Socket-Channelfunctionality
47NetworkChannel 48 * MulticastChannel 49
2.7
Summary
50JP^AJE^JC
2|
"\^FF.AL
'A.'JhjCIIISfl^^UES
•••••*«»*a«««o«»*a*»««««a«««a«»*c**««e*««3.1 Injectsome
knowledge—understanding
IoC and DI 54InversionofControl 54 Dependency Injection 55
TransitioningtoDI 56
3.2 StandardizedDI in
Java
61The@Injectannotation 62 * The©Qualifierannotation 64
The @Named annotation 65 The@Scopeannotation 65
The©Singletonannotation 66* TheProvider<T>interface 66 3.3 Guice 3—the reference
implementation
forDI inJava 67Gettingstartedwith Guice 68 * Sailor's knots—the various
bindings ofGuice 70* Scopingyourinjectedobjects with Guice 73
3.4 Summary 75
4.1
Concurrency
theory—a primer 77ExplainingJava's threadingmodel 77 Design concepts 79 How andwhydo theforces conflict? 80 Sourcesofoverhead 81 A transactionprocessorexample 81
Dependency
Injection
534.2 Block-structured concurrency
(pre-Java
5) 83Synchronizationand locks 83 * Thestatemodelforathread 84
Fullysynchronized objects 85 * Deadlocks 86
Why synchronized! 88 * The volatilekeyword 89
Immutability 90
4.3
Building
blocks for modern concurrentapplications
91Atomicclasses—-Java,util.concurrent,atomic 92
Locks—-java.util.concurrent.locks 93* CountDownLatch 96
ConcurrentHashMap 97 * CopyOnWriteArrayLisl 99
Queues 102
4.4
Controlling
execution 108Modelingtasks 108 * ScheduledThreadPoolExecutor 110
4.5 Thefork/joinframework 111
Asimplefork/join example 112 * ForkJoinTaskand
workstealing 114 * Parallelizingproblems 115
4.6 The
Java Memory
Model (JMM) 1164.7 Summary 118
Class
files
andbytecode
1195.1 Classloadingand class objects 120
Overview—loadingandlinking 120* Verification 121 Classobjects 122 * Classloaders 122 Example—classloaders
inDependency Injection 124
5.2 Usingmethodhandles 125
MethodHandle 126 *
MethodType 127 * Lookingup
method handles 127 * Example—reflectionvs.proxies
vs.MethodHandles 128* Whychoose MethodHandles? 131
5.3 Examiningclass files 132
Introducingjavap 132 * Internalform for
methodsignatures 132 * Theconstantpool 134
5.4
Bytecode
136Example—disassemblingaclass 137 * The runtime
environment 138 * Introductiontoopcodes 140 Load andstoreopcodes 141 * Arithmeticopcodes 141
Execution controlopcodes 142 * Invocationopcodes 143
Platformoperationopcodes 143* Shortcutopcodeforms 144 Example—stringconcatenation 144
CONTENTS
5.5
Invokedynamic
146Howinvokedynamicworks 146 Example—disassembling
aninvokedynamiccall 147
5.6 Summary 149
Understandingperformance tuning
1506.1 Performanceterminology—somebasic definitions 152
Latency 152 * Throughput 152 * Utilization 153
Efficiency 153 Capacity 153 * Scalability 154
Degradation 154
6.2 Apragmatic approachtoperformance analysis 154 Know whatyou're measuring 155 * Know how
totakemeasurements 156* Know what yourperformance
goalsare 157 * Know whentostopoptimizing 157
Know thecostof higherperformance 158 * Know the danger ofpremature optimization 158
6.3 Whatwentwrong?
Why
we havetocare 159Moore's Law—historic andfuture performancetrends 160 Understandingthememory latency hierarchy 161 Whyis
Java performance tuninghard? 162
6.4 A
question
oftime—from the hardware up 163Hardware clocks 163 " The troublewithnanoTime() 164
Therokoftimeinperformance tuning 166* Acasestudy—
understandingcache misses 167
6.5
Garbage
collection 169Basics 170 * Markandsweep 170 *jmap 172
UsefulJVMparameters 176 * Readingthe GClogs 177 Visualizingmemoryusage with VisualVM 178
Escape analysis 181 * ConcurrentMark-Sweep 182
Gl—Java'snewcollector 183
6.6 JIT
compilation
withHotSpot
184Introduction toHotSpot 186 * Inliningmethods 187
Dynamic compilationandmonomorphiccalls 188 Readingthecompilation logs 188
Part 3
Polyglot
programming on theJVM
191
Alternative
JVM languages
1937.1 Java too
clumsy?
Them'sfighting
words! 194The reconciliationsystem 194* Conceptualbasicsof functional programming 196* Mapandfilteridioms 197
7.2
Language zoology
198Interpretedvs. compiled languages 199 * Dynamicvs.
statictyping 199 * Imperativevs.functional languages 200
Reimplementationvs.original 201
7.3 Polyglot programmingon the
JVM
202Whyuse anon-Java language? 203
Up-and-coming languages 204
7.4 Howtochoose a nonjava
language
foryourproject
205Is theprojectarealow-risk? 205 * Does thelanguage intemperate
well withJava? 206 Is theregoodtoolingandtestsupportfor
thelanguage? 207 * How hard is thelanguagetolearn? 207
Are there lotsof developers usingthislanguage? 208
7.5 How theJVMsupportsalternativelanguages 208 Runtimeenvironmentsfornon-Java languages 209
Compilerfictions 209 7.6 Summary 211
Groovy:Java's dynamicfriend
2138.1
Getting
started withGroovy
215Compilingandrunning 216* Groovyconsole 217
8.2
Groovy 101—syntax
and semantics 217Default imports 219 * Numerichandling 219
Variables, dynamicversusstatictypes, andscoping 220
Syntax forlistsandmaps 222
8.3 Differences from
Java—traps
fornewplayers
223Optionalsemicolons and return statements 224
Optionalparentheses formethodparameters 224 Accessmodifiers 225 *Exception handling 225
Equalityin Groovy 225 * Inner classes 226
8.4
Groovy
featuresnot(yet)
inJava 226GroovyBeans 227 * Thesafe-dereferenceoperator 228
CONTENTS
Function literals 230 First-classsupportfor manipulatingcollections 231 First-classsupport for regular expressions 233 SimpleXMLhandling 234
8.5
Interoperating
betweenGroovyandJava 236CallingJava fromGroovy 236 CallingGroovyfromJava 237
8.6 Summary 240
Scala:
powerful
and concise 2419.1 A
quick
tourofScala 242Scalaas aconciselanguage 243 " Matchexpressions 245
Case classes 247 Actors 248
9.2 IsScalarightfor myproject? 249
ComparingScala andJava 250 When and howto start
usingScala 250 Signsthat Scala may notberightfor
yourcurrentproject 251
9.3
Making
codebeautifulagainwith Scala 251Usingthecompilerand the REPL 252 * Type inference 252
Methods 254 * Imports 255 *
Loopsand control
structures 256 m Functional
programminginScala 257 9.4 Scala's
object
model—similar butdifferent 258Everythingisanobject 258 * Constructors 259 Traits 260
Singletonandcompanionobjects 262 Caseclassesand
matchexpressions 264 A cautionarytale 266
9.5 Datastructures and collections 267
List 268 Map 271 Generic types 272 9.6 Introductionto actors 275
All the code'sastage 276 Communicatingwithactors
via the mailbox 276
9.7
Summary
278Clojure: safer
programming
27910.1
Introducing Clojure
280Hello World inClojure 281 * Gettingstarted with
the REPL 281 - Makingamistake 282
Learningtolove the brackets 283
10.2 LookingforClojure—syntaxand semantics 284
Specialforms bootcamp 284 * Lists,vectors,
maps, andsets 285
10.3
Working
with functions andloops inClojure 288Somesimple Clojurefunctions 289 LoopsinClojure 291 Readermacrosanddispatch 292 Functionalprogramming
and closures 293
10.4
Introducing
Clojuresequences 295Lazysequences 297 Sequencesand variable-arity functions 298
10.5
Interoperating
betweenClojureandJava 299CallingJava from Clojure 299 " TheJava type
of Clojurevalues 300 * UsingClojure proxies 301
Exploratory programmingwith the REPL 302
Using Clojure fromJava 302 10.6 Concurrent
Clojure
303Futures andpcalls 304 * Refs 306 * Agents 309
10.7
Summary
310Part 4
Crafting
thepolyglotproject
,11
12
Test-driven
development
31311.1 TDD inanutshell 315
A TDDexamplewithasingleuse case 316 * A TDDexample
withmultipleuse cases 320 *Furtherthinkingonthe
red-green-refactor lifecycle 322 JUnit 324
11.2 Test doubles 325
Dummy object 326 * Stubobject 328 Fakeobject 331
Mockobject 336
11.3
Introducing
ScalaTest 33811.4
Summary
340Build and continuous
integration
34212.1
Getting
started with Maven 3 34512.2 Maven 3—a
quick-start project
346 12.3 Maven 3—theJava7developer
build 348The POM 348 * Runningtheexamples 354
12.4
Jenkins—serving
yourCI needs 357Basicconfiguration 359 * Settingupajob 360
CONTENTS
12.5 Code metrics with Maven andJenkins 365
InstallingJenkins plugins 366 " Makingcode consistent
withCheckstyle 367 Settingthequality barwithFindBugs 369
12.6
Leiningen
372Gettingstarted withLeiningen 372 Leiningen's architecture 373 " Example—HelloLein 373
REPL-oriented TDD withLeiningen 376 PackaginganddeployingwithLeiningen 377
12.7
Summary
379Rapid
webdevelopment
38013.1 The
problem
withJava-basedweb frameworks 381WhyJavacompilationis badfor rapidwebdevelopment 382 Whystatictypingis badfor rapidwebdevelopment 383
13.2 Criteria in
selecting
aweb framework 38313.3
Getting
started with Grails 38513.4 Grails
quick-start
project 386Domainobjectcreation 387 * Test-drivendevelopment 388
Domainobjectpersistence 390 * Test data creation 391
Controllers 392 - GSP/JSPviews 393
Scaffoldingandautomatic UIcreation 395
Rapidturnarounddevelopment 395 13.5 Further Grails
exploration
396Logging 396 * GORM—object-relational mapping 397
Grailsplugins 398
13.6
Getting
started withCompojure
399Hello World withCompojure 399 Ringandroutes 401 Hiccup 402
13.7 A
sample Compojure
project—"AmIanOtterorNot?" 403Settingup "Am Ian Otter" 404 * Corefunctionsin
"Am Ian Otter" 406
13.8
Summary
409Staying
well-grounded
41014.1 Whatto expectin
Java
8 411 Lambdas (a.k.a. closures) 41114.2
Polyglot programming
414Language interoperabilityandmetaobject protocols 415 Multilanguage modularity 416
14.3 Future concurrencytrends 416
The many-core world 417 * Runtime-managed
concurrency 417 14.4 New directions in theJVM 418
VMconvergence 418* Coroutines 419* Tuples 421
14.5
Summary
423appendixA
Java1/7developer—source
code installation 424appendix
B Globpatternsyntaxandexamples 432appendix
CInstalling
alternativeJVMlanguages
434appendix
D DownloadingandinstallingJenkins 441appendix
EJava7developer—theMavenPOM
444