• No results found

The Well-Grounded. Java Developer. Vital techniques of Java 7 and Polyglot Programming BENJAMIN J. EVANS MARTIJN VERBURG MANNING.

N/A
N/A
Protected

Academic year: 2021

Share "The Well-Grounded. Java Developer. Vital techniques of Java 7 and Polyglot Programming BENJAMIN J. EVANS MARTIJN VERBURG MANNING."

Copied!
10
0
0

Loading.... (view fulltext now)

Full text

(1)

The

Well-Grounded

Java

Developer

Vital

techniques

of

Java

7

and

Polyglot Programming

BENJAMIN

J.

EVANS

MARTIJN

VERBURG

II

MANNING Shelter Island
(2)

contents

foreword xvii

preface xix

acknowledgments xxi

aboutthisbook xxiv about the authors xxix about thecoverillustration xxx

Part 1

Developing

with

Java

7

1

Introducingjava

7 3

1.1 The

language

and the

platform

4

1.2 Small is

beautiful—Project

Coin 5

1.3 The

changes

in ProjectCoin 9

Stringsin switch 9 Enhancedsyntaxfor

numeric literals 10 Improved exception handling 12 Try-with-^esources(TWR) 13 Diamondsyntax 16

Simplifiedvarargs methodinvocation 17

1.4

Summary

19

New

I/O

20

2.1

Java

I/O—ahistory 22

Java1.0to1.3 22 • Java1.4 andNIO 23

IntroducingNIO.2 24

(3)

CONTENTS

2.2 Path—a foundation offile-basedI/O 24

CreatingaPath 27 * Retrieving

information

fromaPath 27

Removingredundancies 28 * ConvertingPaths 29

NIO. 2 Path andfava'sexistingFileclass 30

2.3

Dealing

with directories and

directory

trees 30

Findingfilesinadirectory 30 * Walkingthedirectorytree 31

2.4

Filesystem

I/Owith NIO.2 33

Creatinganddeletingfiles 34 Copyingandmovingfiles 35 File attributes 36 * Readingandwritingdataquickly 40 Filechangenotification 41 SeekableByteChannel 42

2.5

Asynchronous

I/O operations 43

Futurestyle 44 * Callbackstyle 46

2.6

Tidying

up Socket-Channel

functionality

47

NetworkChannel 48 * MulticastChannel 49

2.7

Summary

50

JP^AJE^JC

2|

"\^FF.AL

'A.'JhjCIIISfl^^UES

•••••*«»*a«««o«»*a*»««««a«««a«»*c**««e*««

3.1 Injectsome

knowledge—understanding

IoC and DI 54

InversionofControl 54 Dependency Injection 55

TransitioningtoDI 56

3.2 StandardizedDI in

Java

61

The@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 67

Gettingstartedwith Guice 68 * Sailor's knots—the various

bindings ofGuice 70* Scopingyourinjectedobjects with Guice 73

3.4 Summary 75

4.1

Concurrency

theory—a primer 77

ExplainingJava's threadingmodel 77 Design concepts 79 How andwhydo theforces conflict? 80 Sourcesofoverhead 81 A transactionprocessorexample 81

Dependency

Injection

53
(4)

4.2 Block-structured concurrency

(pre-Java

5) 83

Synchronizationand locks 83 * Thestatemodelforathread 84

Fullysynchronized objects 85 * Deadlocks 86

Why synchronized! 88 * The volatilekeyword 89

Immutability 90

4.3

Building

blocks for modern concurrent

applications

91

Atomicclasses—-Java,util.concurrent,atomic 92

Locks—-java.util.concurrent.locks 93* CountDownLatch 96

ConcurrentHashMap 97 * CopyOnWriteArrayLisl 99

Queues 102

4.4

Controlling

execution 108

Modelingtasks 108 * ScheduledThreadPoolExecutor 110

4.5 Thefork/joinframework 111

Asimplefork/join example 112 * ForkJoinTaskand

workstealing 114 * Parallelizingproblems 115

4.6 The

Java Memory

Model (JMM) 116

4.7 Summary 118

Class

files

and

bytecode

119

5.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

136

Example—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

(5)

CONTENTS

5.5

Invokedynamic

146

Howinvokedynamicworks 146 Example—disassembling

aninvokedynamiccall 147

5.6 Summary 149

Understandingperformance tuning

150

6.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 159

Moore's Law—historic andfuture performancetrends 160 Understandingthememory latency hierarchy 161 Whyis

Java performance tuninghard? 162

6.4 A

question

oftime—from the hardware up 163

Hardware clocks 163 " The troublewithnanoTime() 164

Therokoftimeinperformance tuning 166* Acasestudy—

understandingcache misses 167

6.5

Garbage

collection 169

Basics 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

with

HotSpot

184

Introduction toHotSpot 186 * Inliningmethods 187

Dynamic compilationandmonomorphiccalls 188 Readingthecompilation logs 188

(6)

Part 3

Polyglot

programming on the

JVM

191

Alternative

JVM languages

193

7.1 Java too

clumsy?

Them's

fighting

words! 194

The reconciliationsystem 194* Conceptualbasicsof functional programming 196* Mapandfilteridioms 197

7.2

Language zoology

198

Interpretedvs. compiled languages 199 * Dynamicvs.

statictyping 199 * Imperativevs.functional languages 200

Reimplementationvs.original 201

7.3 Polyglot programmingon the

JVM

202

Whyuse anon-Java language? 203

Up-and-coming languages 204

7.4 Howtochoose a nonjava

language

foryour

project

205

Is 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

213

8.1

Getting

started with

Groovy

215

Compilingandrunning 216* Groovyconsole 217

8.2

Groovy 101—syntax

and semantics 217

Default imports 219 * Numerichandling 219

Variables, dynamicversusstatictypes, andscoping 220

Syntax forlistsandmaps 222

8.3 Differences from

Java—traps

fornew

players

223

Optionalsemicolons and return statements 224

Optionalparentheses formethodparameters 224 Accessmodifiers 225 *Exception handling 225

Equalityin Groovy 225 * Inner classes 226

8.4

Groovy

featuresnot

(yet)

inJava 226

GroovyBeans 227 * Thesafe-dereferenceoperator 228

(7)

CONTENTS

Function literals 230 First-classsupportfor manipulatingcollections 231 First-classsupport for regular expressions 233 SimpleXMLhandling 234

8.5

Interoperating

betweenGroovyandJava 236

CallingJava fromGroovy 236 CallingGroovyfromJava 237

8.6 Summary 240

Scala:

powerful

and concise 241

9.1 A

quick

tourofScala 242

Scalaas 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 251

Usingthecompilerand 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 258

Everythingisanobject 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

278

Clojure: safer

programming

279

10.1

Introducing Clojure

280

Hello 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

(8)

10.3

Working

with functions andloops inClojure 288

Somesimple Clojurefunctions 289 LoopsinClojure 291 Readermacrosanddispatch 292 Functionalprogramming

and closures 293

10.4

Introducing

Clojuresequences 295

Lazysequences 297 Sequencesand variable-arity functions 298

10.5

Interoperating

betweenClojureandJava 299

CallingJava from Clojure 299 " TheJava type

of Clojurevalues 300 * UsingClojure proxies 301

Exploratory programmingwith the REPL 302

Using Clojure fromJava 302 10.6 Concurrent

Clojure

303

Futures andpcalls 304 * Refs 306 * Agents 309

10.7

Summary

310

Part 4

Crafting

thepolyglot

project

,

11

12

Test-driven

development

313

11.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 338

11.4

Summary

340

Build and continuous

integration

342

12.1

Getting

started with Maven 3 345

12.2 Maven 3—a

quick-start project

346 12.3 Maven 3—the

Java7developer

build 348

The POM 348 * Runningtheexamples 354

12.4

Jenkins—serving

yourCI needs 357

Basicconfiguration 359 * Settingupajob 360

(9)

CONTENTS

12.5 Code metrics with Maven andJenkins 365

InstallingJenkins plugins 366 " Makingcode consistent

withCheckstyle 367 Settingthequality barwithFindBugs 369

12.6

Leiningen

372

Gettingstarted withLeiningen 372 Leiningen's architecture 373 " Example—HelloLein 373

REPL-oriented TDD withLeiningen 376 PackaginganddeployingwithLeiningen 377

12.7

Summary

379

Rapid

web

development

380

13.1 The

problem

withJava-basedweb frameworks 381

WhyJavacompilationis badfor rapidwebdevelopment 382 Whystatictypingis badfor rapidwebdevelopment 383

13.2 Criteria in

selecting

aweb framework 383

13.3

Getting

started with Grails 385

13.4 Grails

quick-start

project 386

Domainobjectcreation 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

396

Logging 396 * GORM—object-relational mapping 397

Grailsplugins 398

13.6

Getting

started with

Compojure

399

Hello World withCompojure 399 Ringandroutes 401 Hiccup 402

13.7 A

sample Compojure

project—"AmIanOtterorNot?" 403

Settingup "Am Ian Otter" 404 * Corefunctionsin

"Am Ian Otter" 406

13.8

Summary

409

Staying

well-grounded

410

14.1 Whatto expectin

Java

8 411 Lambdas (a.k.a. closures) 411
(10)

14.2

Polyglot programming

414

Language 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

423

appendixA

Java1/7developer—source

code installation 424

appendix

B Globpatternsyntaxandexamples 432

appendix

C

Installing

alternativeJVM

languages

434

appendix

D DownloadingandinstallingJenkins 441

appendix

E

Java7developer—theMavenPOM

444

References

Related documents