The Well-Grounded Java Developer, 2nd Edition (Benjamin J. Evans, Martijn Verburg, Jason Clark) (Z-Library)

Author: Benjamin J. Evans, Martijn Verburg, Jason Clark

技术

Understanding Java from the JVM up gives you a solid foundation to grow your expertise and take on advanced techniques for performance, concurrency, containerization, and more. The Well-Grounded Java Developer, Second Edition introduces both the modern innovations and timeless fundamentals you need to know to become a Java master. Authors Ben Evans, Martijn Verburg, and Jason Clark distill their decades of experience as Java Champions, veteran developers, and key contributors to the Java ecosystem into this clear and practical guide. You’ll discover how Java works under the hood and learn design secrets from Java’s long history. Each concept is illustrated with hands-on examples, including a fully modularized application/library and creating your own multithreaded application. About the technology Java is the beating heart of enterprise software engineering. Developers who really know Java can expect easy job hunting and interesting work. Written by experts with years of boots-on-the-ground experience, this book upgrades your Java skills. It dives into powerful features like modules and concurrency models and even reveals some of Java’s deep secrets. About the book With The Well-Grounded Java Developer, Second Edition you will go beyond feature descriptions and learn how Java operates at the bytecode level. Master high-value techniques for concurrency and performance optimization, along with must-know practices for build, test, and deployment. You’ll even look at alternate JVM languages like Kotlin and Clojure. Digest this book and stand out from the pack. What's inside • The new Java module system • Performance tuning the JVM • Working with Java’s built-in concurrency and expanded options • Programming in Kotlin and Clojure on the JVM • Maximizing CI/CD with Maven and Gradle • Running the JVM in containers • Planning for future JVM releases About the reader For intermediate Java developers.

📄 File Format: PDF
💾 File Size: 18.8 MB
70
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
M A N N I N G Benjamin J. Evans Jason Clark Martijn Verburg Foreword by Heinz Kabutz SECOND EDITION
📄 Page 2
The Well-Grounded Java Developer, Second Edition
📄 Page 3
Praise for the First Edition At the cutting edge of Java development...learn to speak Java 7 and next-gen languages. —Paul Benedict, Corporate Personnel & Associates Buy this book for what's new in Java 7. Keep it open for lessons in expert Java. —Stephen Harrison, PhD, FirstFuel Software A great collection of knowledge on the JVM platform. —Rick Wagner, Red Hat How to become a well-grounded Java developer—and how to stay that way. —From the Foreword by Dr. Heinz Kabutz, The Java Specialists’ Newsletter
📄 Page 4
The Well-Grounded Java Developer SECOND EDITION BENJAMIN J. EVANS, JASON CLARK, AND MARTIJN VERBURG M A N N I N G SHELTER ISLAND
📄 Page 5
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2022 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Elesha Hyde 20 Baldwin Road Technical development editor: Jonathan Thoms PO Box 761 Review editor: Mihaela Batinić Shelter Island, NY 11964 Production editor: Deirdre Hiam Copy editor: Pamela Hunt Proofreader: Jason Everett Technical proofreader: Michael Haller Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN 9781617298875 Printed in the United States of America
📄 Page 6
v brief contents PART 1 FROM 8 TO 11 AND BEYOND!..............................................1 1 ■ Introducing modern Java 3 2 ■ Java modules 26 3 ■ Java 17 55 PART 2 UNDER THE HOOD ..........................................................79 4 ■ Class files and bytecode 81 5 ■ Java concurrency fundamentals 119 6 ■ JDK concurrency libraries 169 7 ■ Understanding Java performance 207 PART 3 NON-JAVA LANGUAGES ON THE JVM................................249 8 ■ Alternative JVM languages 251 9 ■ Kotlin 270 10 ■ Clojure: A different view of programming 299 PART 4 BUILD AND DEPLOYMENT................................................343 11 ■ Building with Gradle and Maven 345
📄 Page 7
BRIEF CONTENTSvi 12 ■ Running Java in containers 401 13 ■ Testing fundamentals 437 14 ■ Testing beyond JUnit 466 PART 5 JAVA FRONTIERS............................................................495 15 ■ Advanced functional programming 497 16 ■ Advanced concurrent programming 537 17 ■ Modern internals 571 18 ■ Future Java 609
📄 Page 8
vii contents foreword xvii preface xix acknowledgements xxii about this book xxiv about the authors xxviii about the cover illustration xxx PART 1 FROM 8 TO 11 AND BEYOND! ....................................1 1 Introducing modern Java 3 1.1 The language and the platform 4 1.2 The new Java release model 6 1.3 Enhanced type inference (var keyword) 9 1.4 Changing the language and the platform 13 Sprinkling some sugar 14 ■ Changing the language 14 JSRs and JEPs 15 ■ Incubating and preview features 15 1.5 Small changes in Java 11 17 Collections factories (JEP 213) 17 ■ Remove enterprise modules (JEP 320) 18 ■ HTTP/2 (Java 11) 19 ■ Single-file source-code programs (JEP 330) 24
📄 Page 9
CONTENTSviii 2 Java modules 26 2.1 Setting the scene 27 Project Jigsaw 28 ■ The module graph 31 ■ Protecting the internals 32 ■ New access control semantics 33 2.2 Basic modules syntax 34 Exporting and requiring 36 ■ Transitivity 37 2.3 Loading modules 37 Platform modules 38 ■ Application modules 39 ■ Automatic modules 39 ■ Unnamed module 40 2.4 Building a first modular app 40 Command-line switches for modules 41 ■ Executing a modular app 43 ■ Modules and reflection 45 2.5 Architecting for modules 46 Split packages 47 ■ Java 8 Compact Profiles 47 ■ Multi-release JARs 49 2.6 Beyond modules 52 3 Java 17 55 3.1 Text Blocks 55 3.2 Switch Expressions 57 3.3 Records 60 Nominal typing 66 ■ Compact record constructors 67 3.4 Sealed Types 69 3.5 New form of instanceof 74 3.6 Pattern Matching and preview features 75 PART 2 UNDER THE HOOD ................................................79 4 Class files and bytecode 81 4.1 Class loading and class objects 82 Loading and linking 83 ■ Class objects 85 4.2 Class loaders 86 Custom class loading 88 ■ Modules and class loading 95 4.3 Examining class files 95 Introducing javap 96 ■ Internal form for method signatures 96 The constant pool 98
📄 Page 10
CONTENTS ix 4.4 Bytecode 101 Disassembling a class 101 ■ The runtime environment 103 Introduction to opcodes 105 ■ Load and store opcodes 106 Arithmetic opcodes 107 ■ Execution flow control opcodes 108 Invocation opcodes 109 ■ Platform operation opcodes 112 Shortcut opcode forms 112 4.5 Reflection 113 Introducing reflection 114 ■ Combining class loading and reflection 116 ■ Problems with reflection 117 5 Java concurrency fundamentals 119 5.1 Concurrency theory primer 120 But I already know about Thread 120 ■ Hardware 121 Amdahl’s law 121 ■ Explaining Java’s threading model 123 Lessons learned 124 5.2 Design concepts 124 Safety and concurrent type safety 125 ■ Liveness 126 Performance 126 ■ Reusability 126 ■ How and why do the forces conflict? 127 ■ Sources of overhead 127 5.3 Block-structured concurrency (pre-Java 5) 128 Synchronization and locks 128 ■ The state model for a thread 130 ■ Fully synchronized objects 131 ■ Deadlocks 132 Why synchronized? 135 ■ The volatile keyword 137 ■ Thread states and methods 137 ■ Immutability 144 5.4 The Java Memory Model (JMM) 147 5.5 Understanding concurrency through bytecode 149 Lost Update 151 ■ Synchronization in bytecode 153 Synchronized methods 157 ■ Unsynchronized reads 158 Deadlock revisited 160 ■ Deadlock resolved, revisited 162 Volatile access 166 6 JDK concurrency libraries 169 6.1 Building blocks for modern concurrent applications 169 6.2 Atomic classes 170 6.3 Lock classes 172 Condition objects 173 6.4 CountDownLatch 174
📄 Page 11
CONTENTSx 6.5 ConcurrentHashMap 176 Understanding a simplified HashMap 176 ■ Limitations of Dictionary 179 ■ Approaches to a concurrent Dictionary 180 Using ConcurrentHashMap 182 6.6 CopyOnWriteArrayList 185 6.7 Blocking queues 188 Using BlockingQueue APIs 194 ■ Using WorkUnit 196 6.8 Futures 197 CompletableFuture 198 6.9 Tasks and execution 200 Modeling tasks 200 ■ Executors 202 ■ Single-threaded executor 203 ■ Fixed-thread pool 204 ■ Cached thread pool 205 ■ ScheduledThreadPoolExecutor 205 7 Understanding Java performance 207 7.1 Performance terminology: Some basic definitions 209 Latency 210 ■ Throughput 210 ■ Utilization 210 Efficiency 211 ■ Capacity 211 ■ Scalability 211 Degradation 211 7.2 A pragmatic approach to performance analysis 212 Know what you’re measuring 212 ■ Know how to take measurements 213 ■ Know what your performance goals are 214 ■ Know when to stop 215 ■ Know the cost of achieving higher performance 215 ■ Know the dangers of premature optimization 216 7.3 What went wrong? Why do we have to care? 217 Moore’s law 217 ■ Understanding the memory latency hierarchy 219 7.4 Why is Java performance tuning hard? 220 The role of time in performance tuning 221 ■ Understanding cache misses 222 7.5 Garbage collection 224 Basics 225 ■ Mark and sweep 225 ■ Areas of memory 227 Young collections 228 ■ Full collections 228 ■ Safepoints 228 G1: Java’s default collector 229 ■ The Parallel collector 231 GC configuration parameters 232
📄 Page 12
CONTENTS xi 7.6 JIT compilation with HotSpot 233 Why have dynamic compilation? 234 ■ Introduction to HotSpot 235 Inlining methods 236 ■ Dynamic compilation and monomorphic calls 236 ■ Reading the compilation logs 237 ■ Deoptimization 238 7.7 JDK Flight Recorder 238 Flight Recorder 239 ■ Mission Control 240 PART 3 NON-JAVA LANGUAGES ON THE JVM ......................249 8 Alternative JVM languages 251 8.1 Language zoology 252 Interpreted vs. compiled languages 252 ■ Dynamic vs. static typing 253 ■ Imperative vs. functional languages 254 Reimplementation vs. original 255 8.2 Polyglot programming on the JVM 256 Why use a non-Java language? 257 ■ Up-and-coming languages 259 ■ Languages we could have picked but didn’t 260 8.3 How to choose a non-Java language for your project 262 Is the project area low-risk? 262 ■ Does the language interoperate well with Java? 263 ■ Is there good tooling and test support for the language? 264 ■ How hard is the language to learn? 264 Are there lots of developers using this language? 264 8.4 How the JVM supports alternative languages 265 Performance 266 ■ Runtime environments for non-Java languages 266 ■ Compiler fictions 267 9 Kotlin 270 9.1 Why use Kotlin? 271 Installing 271 9.2 Convenience and conciseness 271 Starting with less 271 ■ Variables 272 ■ Equality 273 Functions 273 ■ Collections 277 ■ Express yourself 279 9.3 A different view of classes and objects 281 Data classes 286 9.4 Safety 287 Null safety 288 ■ Smart casting 289 9.5 Concurrency 291 9.6 Java interoperability 294
📄 Page 13
CONTENTSxii 10 Clojure: A different view of programming 299 10.1 Introducing Clojure 300 Hello World in Clojure 302 ■ Getting started with the REPL 303 Making a mistake 305 ■ Learning to love the brackets 308 10.2 Looking for Clojure: Syntax and semantics 309 Special forms bootcamp 309 ■ Lists, vectors, maps, and sets 312 Arithmetic, equality, and other operations 315 ■ Working with functions in Clojure 316 ■ Loops in Clojure 319 ■ Reader macros and dispatch 321 10.3 Functional programming and closures 323 10.4 Introducing Clojure sequences 325 Sequences and variable-arity functions 329 10.5 Interoperating between Clojure and Java 330 Calling Java from Clojure 331 ■ The nature of Clojure calls 332 The Java type of Clojure values 332 ■ Using Clojure proxies 333 Exploratory programming with the REPL 334 ■ Using Clojure from Java 335 10.6 Macros 335 PART 4 BUILD AND DEPLOYMENT ......................................343 11 Building with Gradle and Maven 345 11.1 Why build tools matter for a well-grounded developer 345 Automating tedious operations 346 ■ Managing dependencies 346 ■ Ensuring consistency between developers 349 11.2 Maven 350 The build lifecycle 350 ■ Commands/POM intro 351 Building 353 ■ Controlling the manifest 354 ■ Adding another language 355 ■ Testing 357 ■ Dependency management 360 ■ Reviewing 364 ■ Moving beyond Java 8 365 ■ Multirelease JARs in Maven 366 ■ Maven and modules 369 ■ Authoring Maven plugins 372 11.3 Gradle 376 Installing Gradle 376 ■ Tasks 377 ■ What’s in a script? 378 Using plugins 378 ■ Building 379 ■ Work avoidance 381 Dependencies in Gradle 382 ■ Adding Kotlin 387 ■ Testing 388 Automating static analysis 389 ■ Moving beyond Java 8 390 Using Gradle with modules 391 ■ Customizing 397
📄 Page 14
CONTENTS xiii 12 Running Java in containers 401 12.1 Why containers matter for a well-grounded developer 402 Host operating systems vs. virtual machines vs. containers 402 Benefits of containers 404 ■ Drawbacks of containers 405 12.2 Docker fundamentals 406 Building Docker images 406 ■ Running Docker containers 409 12.3 Developing Java applications with Docker 411 Selecting your base image 411 ■ Building an image with Gradle 412 ■ Running the build in Docker 414 ■ Ports and hosts 416 ■ Local development with Docker Compose 418 Debugging in Docker 421 ■ Logging with Docker 423 12.4 Kubernetes 424 12.5 Observability and performance 432 Observability 432 ■ Performance in containers 434 13 Testing fundamentals 437 13.1 Why we test 438 13.2 How we test 438 13.3 Test-driven development 441 TDD in a nutshell 442 ■ A TDD example with a single use case 443 13.4 Test doubles 449 Dummy object 449 ■ Stub object 451 ■ Fake object 454 Mock object 456 ■ Problems with mocking 457 13.5 From JUnit 4 to 5 459 14 Testing beyond JUnit 466 14.1 Integration testing with Testcontainers 466 Installing testcontainers 467 ■ An example with Redis 467 Gathering container logs 471 ■ An example with Postgres 472 An example for end-to-end testing with Selenium 474 14.2 Specification-style testing with Spek and Kotlin 476 14.3 Property-based testing with Clojure 481 clojure.test 481 ■ clojure.spec 483 ■ test.check 487 clojure.spec and test.check 492
📄 Page 15
CONTENTSxiv PART 5 JAVA FRONTIERS..................................................495 15 Advanced functional programming 497 15.1 Introduction to functional programming concepts 498 Pure functions 498 ■ Immutability 498 ■ Higher-order functions 499 ■ Recursion 500 ■ Closures 500 Laziness 501 ■ Currying and partial application 502 15.2 Limitations of Java as a FP language 502 Pure functions 503 ■ Mutability 503 ■ Higher-order functions 505 ■ Recursion 506 ■ Closures 509 Laziness 511 ■ Currying and partial application 513 Java’s type system and collections 514 15.3 Kotlin FP 515 Pure and higher-order functions 516 ■ Closures 517 Currying and partial application 518 ■ Immutability 519 Tail recursion 522 ■ Lazy evaluation 525 ■ Sequences 526 15.4 Clojure FP 531 Comprehensions 531 ■ Lazy sequences 532 ■ Currying in Clojure 535 16 Advanced concurrent programming 537 16.1 The Fork/Join framework 538 A simple F/J example 539 ■ Parallelizing problems for F/J 542 Work-stealing algorithms 543 16.2 Concurrency and functional programming 544 CompletableFuture revisited 544 ■ Parallel streams 547 16.3 Under the hood with Kotlin coroutines 549 How coroutines work 549 ■ Coroutine scoping and dispatching 554 16.4 Concurrent Clojure 557 Persistent data structures 557 ■ Futures and pcalls 563 Software transactional memory 565 ■ Agents 569 17 Modern internals 571 17.1 Introducing JVM internals: Method invocation 571 Invoking virtual methods 572 ■ Invoking interface methods 575 Invoking “special” methods 576 ■ Final methods 578
📄 Page 16
CONTENTS xv 17.2 Reflection internals 578 17.3 Method handles 583 MethodHandle 583 ■ MethodType 584 ■ Looking up method handles 585 ■ Reflection vs. proxies vs. method handles 586 17.4 Invokedynamic 589 Implementing lambda expressions 591 17.5 Small internal changes 593 String concatenation 593 ■ Compact strings 596 Nestmates 597 17.6 Unsafe 600 17.7 Replacing Unsafe with supported APIs 604 VarHandles 605 ■ Hidden classes 607 18 Future Java 609 18.1 Project Amber 610 18.2 Project Panama 612 Foreign Function and Memory API 612 18.3 Project Loom 618 Virtual threads 621 ■ Thread builders 622 ■ Programming with virtual threads 623 ■ When will Project Loom arrive? 625 18.4 Project Valhalla 626 Changing the language model 630 ■ Consequences of value objects 630 ■ Generics revisited 633 18.5 Java 18 633 appendix A Selecting your Java 637 appendix B Recap of streams in Java 8 640 index 649
📄 Page 17
(This page has no text content)
📄 Page 18
xvii foreword Well-grounded? You mean, “well-rounded”? Two years of pandemic would do that without the need for a book. Merriam-Webster defines well-grounded as “having a firm foundation.” I like that. We want to have a firm foundation in Java—a practical knowledge of what we need to know to call ourselves Java experts. This book picks up where Effective Java stops. This is the second edition of a great book. The first taught us all that we needed to know for Java 7. That seems like eons ago. Java 7 belonged to another age, when fea- tures were added to the language at best every three years. Back then, it was easy to keep versions apart. Java 5? Generics and enums. Java 7? try-with-resource. Java 8? Streams and lambdas. Those comfortable easy days ended when Oracle introduced the six-month cycle. Records—were those Java 14, 15, or 17? Enhanced Switch? Was that already in Java 11? The fast release cycle is great for programmers who work for adventurous compa- nies. Every six months, they get new toys to play with. They might even get to try out previews of what will come next. The myriad of new features is wonderful for pro- grammers, but not so nice for authors. Before the ink has dried, a new feature release makes a bunch of things obsolete. Ben, Jason, and Martijn have done a fantastic job with this new Java book. The basic premise remains the same. In my words: “If you wanted to hire a professional Java programmer, what would you expect them to already know? What skills would they need to prove they are well grounded?”
📄 Page 19
FOREWORDxviii This new version of the book is as current as is possible with the six-month release cadence. At the same time, the authors don’t overwhelm us with new stuff. The stark reality is that most enterprises are still stuck on an older version of Java. Even with Java 18 released, a lot of banks, insurance companies, and government departments are still on Java 8. This book is about 200 pages longer than the previous edition. The fonts are a bit larger—well, we have all aged by nine years, haven’t we? But the margins are smaller. Quite a few of the sections have completely new content. This is one case where the new edition does not make the old one obsolete. Both belong on a serious Java pro- grammer’s bookshelf. Benjamin J. Evans, Jason R. Clark, and Martijn Verburg are Java experts. They hold senior Java positions at Red Hat, New Relic, and Microsoft. Let’s take advantage of their collective wisdom. This book will help us discover areas of weakness that we can then improve on. In the end, with enough work, we can call ourselves Well-Grounded Java programmers. HEINZ KABUTZ THE JAVA SPECIALISTS’ NEWSLETTER
📄 Page 20
xix preface The first edition of this book started life as a set of training notes written for new grad- uate developers in the foreign exchange department of a bank. One of us (Ben), look- ing at the existing books on the market, found a lack of up-to-date material aimed at Java developers who wanted to level up. Partway through writing that material, he found he was writing that missing book and enlisted Martijn to help. That was more than 10 years ago—we were writing as Java 7 was being developed— and the world is very different now. In response, the book has changed substantially since the first edition. So, although our original primary goals were to introduce top- ics like ■ Polyglot programming ■ Dependency injection ■ Multithreaded programming ■ Sound build and CI practices ■ What’s new in Java 7 when we came to write the second edition, we found that we needed to make some changes, including ■ Trimming down polyglot a bit ■ Adding a new emphasis on functional programming ■ Enhancing the discussion of multithreading ■ Putting a different spin on build and deploy (including containers) ■ Talking about what’s new in Java 11 and 17
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List