Java Coding Problems - Second Edition

Book description

Stay on top of the new Java features (up to JDK 21) and find efficient solutions for your programming woes. With over 250 problems and solutions, you'll learn new ways to deal with real-world coding tasks and answers to common interview questions. Purchase of the print or Kindle book includes a free PDF eBook

Key Features

  • Solve Java programming challenges and get interview-ready with the power of modern Java 21
  • Test your Java skills using language features, algorithms, data structures, and design patterns
  • Explore tons of examples, all fully refreshed for this edition, meant to help you accommodate JDK 12 to JDK 21

Book Description

The super-fast evolution of the JDK between versions 12 and 21 has made the learning curve of modern Java steeper, and increased the time needed to learn it. This book will make your learning journey quicker and increase your willingness to try Java’s new features by explaining the correct practices and decisions related to complexity, performance, readability, and more.

Java Coding Problems takes you through Java’s latest features but doesn’t always advocate the use of new solutions — instead, it focuses on revealing the trade-offs involved in deciding what the best solution is for a certain problem.

There are more than two hundred brand new and carefully selected problems in this second edition, chosen to highlight and cover the core everyday challenges of a Java programmer.

Apart from providing a comprehensive compendium of problem solutions based on real-world examples, this book will also give you the confidence to answer questions relating to matching particular streams and methods to various problems.

By the end of this book you will have gained a strong understanding of Java’s new features and have the confidence to develop and choose the right solutions to your problems.

What you will learn

  • Adopt the latest JDK 21 features in your applications
  • Explore Records, Record Patterns, Record serialization and so on
  • Work with Sealed Classes and Interfaces for increasing encapsulation
  • Learn how to exploit Context-Specific Deserialization Filters
  • Solve problems relating to collections and esoteric data structures
  • Learn advanced techniques for extending the Java functional API
  • Explore the brand-new Socket API and Simple Web Server
  • Tackle modern Garbage Collectors and Dynamic CDS Archives

Who this book is for

If you are a Java developer who wants to level-up by solving real-world problems, then this book is for you. Working knowledge of the Java programming language is required to get the most out of this book

Table of contents

  1. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Get in touch
  2. Text Blocks, Locales, Numbers, and Math
    1. Problems
    2. 1. Creating a multiline SQL, JSON, and HTML string
      1. Before JDK 8
      2. Starting with JDK 8
      3. Introducing text blocks (JDK 13/15)
        1. Hooking text blocks syntax
    3. 2. Exemplifying the usage of text block delimiters
    4. 3. Working with indentation in text blocks
      1. Shifting the closing delimiter and/or the content
      2. Using indentation methods
    5. 4. Removing incidental white spaces in text blocks
    6. 5. Using text blocks just for readability
    7. 6. Escaping quotes and line terminators in text blocks
    8. 7. Translating escape sequences programmatically
    9. 8. Formatting text blocks with variables/expressions
    10. 9. Adding comments in text blocks
    11. 10. Mixing ordinary string literals with text blocks
    12. 11. Mixing regular expression with text blocks
    13. 12. Checking if two text blocks are isomorphic
    14. 13. Concatenating strings versus StringBuilder
      1. JDK 8
      2. JDK 11
    15. 14. Converting int to String
    16. 15. Introducing string templates
      1. What’s a string template?
      2. The STR template processor
      3. The FMT template processor
      4. The RAW template processor
    17. 16. Writing a custom template processor
    18. 17. Creating a Locale
    19. 18. Customizing localized date-time formats
    20. 19. Restoring Always-Strict Floating-Point semantics
    21. 20. Computing mathematical absolute value for int/long and result overflow
    22. 21. Computing the quotient of the arguments and result overflow
    23. 22. Computing the largest/smallest value that is less/greater than or equal to the algebraic quotient
    24. 23. Getting integral and fractional parts from a double
    25. 24. Testing if a double number is an integer
    26. 25. Hooking Java (un)signed integers in a nutshell
    27. 26. Returning the flooring/ceiling modulus
    28. 27. Collecting all prime factors of a given number
    29. 28. Computing the square root of a number using the Babylonian method
    30. 29. Rounding a float number to specified decimals
    31. 30. Clamping a value between min and max
    32. 31. Multiply two integers without using loops, multiplication, bitwise, division, and operators
    33. 32. Using TAU
      1. What is TAU?
    34. 33. Selecting a pseudo-random number generator
      1. Choosing an algorithm by name
      2. Choosing an algorithm by property
    35. 34. Filling a long array with pseudo-random numbers
    36. 35. Creating a stream of pseudo-random generators
    37. 36. Getting a legacy pseudo-random generator from new ones of JDK 17
    38. 37. Using pseudo-random generators in a thread-safe fashion (multithreaded environments)
    39. Summary
  3. Objects, Immutability, Switch Expressions, and Pattern Matching
    1. Problems
    2. 38. Explain and exemplifying UTF-8, UTF-16, and UTF-32
      1. Introducing ASCII encoding scheme (or single-byte encoding)
      2. Introducing multi-byte encoding
        1. Unicode
      3. Java and Unicode
        1. JDK 18 defaults the charset to UTF-8
    3. 39. Checking a sub-range in the range from 0 to length
    4. 40. Returning an identity string
    5. 41. Hooking unnamed classes and instance main methods
    6. 42. Adding code snippets in Java API documentation
      1. Adding attributes
      2. Using markup comments and regions
        1. Highlighting
        2. Linking
        3. Modifying the code’s text
      3. Using external snippets
        1. Regions in external snippets
    7. 43. Invoking default methods from Proxy instances
      1. JDK 8
      2. JDK 9+, pre-JDK 16
      3. JDK 16+
    8. 44. Converting between bytes and hex-encoded strings
      1. JDK 17+
    9. 45. Exemplify the initialization-on-demand holder design pattern
      1. Static vs. non-static blocks
      2. Nested classes
      3. Tackling the initialization-on-demand holder design pattern
      4. JDK 16+
    10. 46. Adding nested classes in anonymous classes
      1. JDK 16+
    11. 47. Exemplify erasure vs. overloading
      1. Erasure in a nutshell
        1. Erasure of generic types
        2. Erasure and bridge methods
        3. Type erasure and heap pollution
      2. Polymorphic overloading in a nutshell
      3. Erasure vs. overloading
    12. 48. Xlinting default constructors
    13. 49. Working with the receiver parameter
    14. 50. Implementing an immutable stack
    15. 51. Revealing a common mistake with Strings
    16. 52. Using the enhanced NullPointerException
      1. WARNING 1! NPE when calling an instance method via a null object
      2. WARNING 2! NPE when accessing (or modifying) the field of a null object
      3. WARNING 3! NPE when null is passed in the method argument
      4. WARNING 4! NPE when accessing the index value of a null array/collection
      5. WARNING 5! NPE when accessing a field via a getter
    17. 53. Using yield in switch expressions
    18. 54. Tackling the case null clause in switch
    19. 55. Taking on the hard way to discover equals()
    20. 56. Hooking instanceof in a nutshell
    21. 57. Introducing pattern matching
      1. The scope of binding variables in pattern matching
      2. Guarded patterns
      3. Type coverage
      4. Current status of pattern matching
    22. 58. Introducing type pattern matching for instanceof
    23. 59. Handling the scope of a binding variable in type patterns for instanceof
    24. 60. Rewriting equals() via type patterns for instanceof
    25. 61. Tackling type patterns for instanceof and generics
    26. 62. Tackling type patterns for instanceof and streams
    27. 63. Introducing type pattern matching for switch
    28. 64. Adding guarded pattern labels in switch
    29. 65. Dealing with pattern label dominance in switch
    30. 66. Dealing with completeness (type coverage) in pattern labels for switch
    31. 67. Understanding the unconditional patterns and nulls in switch expressions
    32. Summary
  4. Working with Date and Time
    1. Problems
    2. 68. Defining a day period
      1. Before JDK 16
      2. JDK 16+
    3. 69. Converting between Date and YearMonth
    4. 70. Converting between int and YearMonth
    5. 71. Converting week/year to Date
    6. 72. Checking for a leap year
    7. 73. Calculating the quarter of a given date
    8. 74. Getting the first and last day of a quarter
    9. 75. Extracting the months from a given quarter
    10. 76. Computing pregnancy due date
    11. 77. Implementing a stopwatch
    12. 78. Extracting the count of milliseconds since midnight
    13. 79. Splitting a date-time range into equal intervals
    14. 80. Explaining the difference between Clock.systemUTC() and Clock.systemDefaultZone()
    15. 81. Displaying the names of the days of the week
    16. 82. Getting the first and last day of the year
    17. 83. Getting the first and last day of the week
    18. 84. Calculating the middle of the month
    19. 85. Getting the number of quarters between two dates
    20. 86. Converting Calendar to LocalDateTime
    21. 87. Getting the number of weeks between two dates
    22. Summary
  5. Records and Record Patterns
    1. Problems
    2. 88. Declaring a Java record
    3. 89. Introducing the canonical and compact constructors for records
      1. Handling validation
      2. Reassigning components
      3. Defensive copies of the given components
    4. 90. Adding more artifacts in a record
    5. 91. Iterating what we cannot have in a record
      1. A record cannot extend another class
      2. A record cannot be extended
      3. A record cannot be enriched with instance fields
      4. A record cannot have private canonical constructors
      5. A record cannot have setters
    6. 92. Defining multiple constructors in a record
    7. 93. Implementing interfaces in records
    8. 94. Understanding record serialization
      1. How serialization/deserialization works
      2. Serializing/deserializing gacContainer (a typical Java class)
        1. Deserializing a malicious stream
      3. Serializing/deserializing gacContainerR (a Java record)
        1. Deserializing a malicious stream
      4. Refactoring legacy serialization
    9. 95. Invoking the canonical constructor via reflection
    10. 96. Using records in streams
    11. 97. Introducing record patterns for instanceof
      1. Nested records and record patterns
    12. 98. Introducing record patterns for switch
    13. 99. Tackling guarded record patterns
    14. 100. Using generic records in record patterns
      1. Type argument inference
      2. Type argument inference and nested records
    15. 101. Handling nulls in nested record patterns
    16. 102. Simplifying expressions via record patterns
    17. 103. Hooking unnamed patterns and variables
      1. Unnamed patterns
      2. Unnamed variables
        1. In a catch block
        2. In a for loop
        3. In an assignment that ignores the result
        4. In try-with-resources
        5. In lambda expressions
    18. 104. Tackling records in Spring Boot
      1. Using records in controllers
      2. Using records with templates
      3. Using records for configuration
      4. Record and dependency injection
    19. 105. Tackling records in JPA
      1. DTO via record constructor
      2. DTO via record and JPA constructor expression
      3. DTO via record and result transformer
      4. DTO via record and JdbcTemplate
      5. Team up Java records and @Embeddable
    20. 106. Tackling records in jOOQ
    21. Summary
  6. Arrays, Collections, and Data Structures
    1. Problems
    2. 107. Introducing parallel computations with arrays
    3. 108. Covering the Vector API’s structure and terminology
      1. The vector element type
      2. The vector shape
      3. The vector species
      4. Vector lanes
      5. Vector operations
      6. Creating vectors
        1. Creating vectors of zeros
        2. Creating vectors of the same primitive value
        3. Creating vectors from Java arrays
        4. Creating vectors from memory segments
    4. 109. Summing two arrays via the Vector API
    5. 110. Summing two arrays unrolled via the Vector API
    6. 111. Benchmarking the Vector API
    7. 112. Applying the Vector API to compute FMA
    8. 113. Multiplying matrices via the Vector API
    9. 114. Hooking the image negative filter with the Vector API
    10. 115. Dissecting factory methods for collections
      1. Factory methods for maps
      2. Factory methods for lists
      3. Factory methods for sets
    11. 116. Getting a list from a stream
    12. 117. Handling map capacity
    13. 118. Tackling Sequenced Collections
      1. Applying the Sequenced Collections API to lists
        1. Applying the Sequenced Collections API to ArrayList and LinkedList
      2. Applying the Sequenced Collections API to sets
        1. Applying the Sequenced Collections API to HashSet
        2. Applying the Sequenced Collections API to LinkedHashSet
        3. Applying the Sequenced Collections API to TreeSet
      3. Applying the Sequenced Collections API to maps
        1. Applying the Sequenced Collections API to LinkedHashMap
        2. Applying the Sequenced Collections API to SortedMap (TreeMap)
    14. 119. Introducing the Rope data structure
      1. Implementing indexAt(Node node, int index)
      2. Implementing concat(Node node1, Node node2)
      3. Implementing insert(Node node, int index, String str)
      4. Implementing delete(Node node, int start, int end)
      5. Implementing split(Node node, int index)
    15. 120. Introducing the Skip List data structure
      1. Implementing contains(Integer data)
      2. Implementing insert(Integer data)
      3. Implementing delete(Integer data)
    16. 121. Introducing the K-D Tree data structure
      1. Inserting into a K-D Tree
      2. Finding the nearest neighbor
    17. 122. Introducing the Zipper data structure
    18. 123. Introducing the Binomial Heap data structure
      1. Implementing insert(int key)
      2. Implementing findMin()
      3. Implementing extractMin()
      4. Implementing decreaseKey(int key, int newKey)
      5. Implementing delete(int key)
      6. Implementing unionHeap(BinomialHeap heap)
    19. 124. Introducing the Fibonacci Heap data structure
    20. 125. Introducing the Pairing Heap data structure
    21. 126. Introducing the Huffman Coding data structure
      1. Encoding the string
      2. Decoding the string
    22. 127. Introducing the Splay Tree data structure
    23. 128. Introducing the Interval Tree data structure
      1. Implementing insert(Interval interval)
    24. 129. Introducing the Unrolled Linked List data structure
    25. 130. Implementing join algorithms
      1. Nested Loop Join
      2. Hash Join
      3. Sort Merge Join
    26. Summary
  7. Java I/O: Context-Specific Deserialization Filters
    1. Problems
    2. 131. Serializing objects to byte arrays
    3. 132. Serializing objects to strings
    4. 133. Serializing objects to XML
    5. 134. Introducing JDK 9 deserialization filters
      1. Pattern-based filters
        1. Applying a pattern-based filter per application
        2. Applying a pattern-based filter to all applications in a process
      2. ObjectInputFilter-based filters
    6. 135. Implementing a custom pattern-based ObjectInputFilter
    7. 136. Implementing a custom class ObjectInputFilter
    8. 137. Implementing a custom method ObjectInputFilter
    9. 138. Implementing a custom lambda ObjectInputFilter
    10. 139. Avoiding StackOverflowError at deserialization
    11. 140. Avoiding DoS attacks at deserialization
    12. 141. Introducing JDK 17 easy filter creation
    13. 142. Tackling context-specific deserialization filters
      1. Applying a Filter Factory per application
      2. Applying a Filter Factory to all applications in a process
      3. Applying a Filter Factory via ObjectInputFilter.Config
      4. Implementing a Filter Factory
    14. 143. Monitoring deserialization via JFR
    15. Summary
  8. Foreign (Function) Memory API
    1. Problems
    2. 144. Introducing Java Native Interface (JNI)
      1. Generating the header (.h) file
      2. Implementing the modern_challenge_Main.cpp
      3. Compiling the C source code
      4. Generating the native shared library
      5. Finally, run the code
    3. 145. Introducing Java Native Access (JNA)
      1. Implementing the .cpp and .h files
      2. Compiling the C source code
      3. Generating the native shared library
      4. Finally, run the code
    4. 146. Introducing Java Native Runtime (JNR)
    5. 147. Motivating and introducing Project Panama
    6. 148. Introducing Panama’s architecture and terminology
    7. 149. Introducing Arena and MemorySegment
      1. Introducing memory layouts (ValueLayout)
        1. Allocating memory segments of value layouts
        2. Setting/getting the content of a memory segment
        3. Working with Java strings
    8. 150. Allocating arrays into memory segments
    9. 151. Understanding addresses (pointers)
    10. 152. Introducing the sequence layout
      1. Introducing PathElement
      2. Introducing VarHandle
      3. Putting PathElement and VarHandle together
      4. Working with nested sequence layouts
    11. 153. Shaping C-like structs into memory segments
      1. Introducing StructLayout
    12. 154. Shaping C-like unions into memory segments
      1. Introducing UnionLayout
    13. 155. Introducing PaddingLayout
      1. Hooking size, alignment, stride, and padding
        1. Hooking size
        2. Hooking alignment
        3. Hooking stride
        4. Hooking padding
      2. Adding implicit extra space (implicit padding) to validate alignment
      3. Adding explicit extra space (explicit padding) to validate alignment
    14. 156. Copying and slicing memory segments
      1. Copying a segment
      2. Copying a part of the segment into another segment (1)
      3. Copying a segment into an on-heap array
      4. Copying an on-heap array into a segment
      5. Copying a part of the segment into another segment (2)
      6. Slicing a segment
        1. Using asOverlappingSlice()
        2. Using segmentOffset()
    15. 157. Tackling the slicing allocator
    16. 158. Introducing the slice handle
    17. 159. Introducing layout flattening
    18. 160. Introducing layout reshaping
    19. 161. Introducing the layout spreader
    20. 162. Introducing the memory segment view VarHandle
    21. 163. Streaming memory segments
    22. 164. Tackling mapped memory segments
    23. 165. Introducing the Foreign Linker API
    24. 166. Calling the sumTwoInt() foreign function
    25. 167. Calling the modf() foreign function
    26. 168. Calling the strcat() foreign function
    27. 169. Calling the bsearch() foreign function
    28. 170. Introducing Jextract
    29. 171. Generating native binding for modf()
    30. Summary
  9. Sealed and Hidden Classes
    1. Problems
    2. 172. Creating an electrical panel (hierarchy of classes)
    3. 173. Closing the electrical panel before JDK 17
      1. Applying the final modifier
      2. Defining package-private constructors
      3. Declaring classes/interfaces as non-public
      4. Throwing everything in a module
      5. Conclusion
    4. 174. Introducing JDK 17 sealed classes
    5. 175. Introducing the permits clause
      1. Working with sealed classes in separate sources (same package)
      2. Working with sealed classes in separate packages
    6. 176. Closing the electrical panel after JDK 17
    7. 177. Combining sealed classes and records
    8. 178. Hooking sealed classes and instanceof
    9. 179. Hooking sealed classes in switch
    10. 180. Reinterpreting the Visitor pattern via sealed classes and type pattern matching for switch
    11. 181. Getting info about sealed classes (using reflection)
    12. 182. Listing the top three benefits of sealed classes
    13. 183. Briefly introducing hidden classes
    14. 184. Creating a hidden class
    15. Summary
  10. Functional Style Programming – Extending APIs
    1. Problems
    2. 185. Working with mapMulti()
    3. 186. Streaming custom code to map
    4. 187. Exemplifying a method reference vs. a lamda
      1. Scenario 1: Calling printReset()
      2. Scenario 2: Calling static printNoReset()
      3. Conclusion
    5. 188. Hooking lambda laziness via Supplier/Consumer
    6. 189. Refactoring code to add lambda laziness
      1. Fixing in imperative fashion
      2. Fixing in functional fashion
    7. 190. Writing a Function<String, T> for parsing data
    8. 191. Composing predicates in a Stream’s filters
    9. 192. Filtering nested collections with Streams
    10. 193. Using BiPredicate
    11. 194. Building a dynamic predicate for a custom model
    12. 195. Building a dynamic predicate from a custom map of conditions
    13. 196. Logging in predicates
    14. 197. Extending Stream with containsAll() and containsAny()
      1. Exposing containsAll/Any() via a custom interface
      2. Exposing containsAll/Any() via an extension of Stream
    15. 198. Extending Stream with removeAll() and retainAll()
      1. Exposing removeAll()/retainAll() via a custom interface
      2. Exposing removeAll/retainAll() via an extension of Stream
    16. 199. Introducing stream comparators
      1. Sorting via natural order
      2. Reversing the natural order
      3. Sorting and nulls
      4. Writing custom comparators
    17. 200. Sorting a map
    18. 201. Filtering a map
    19. 202. Creating a custom collector via Collector.of()
      1. Writing a custom collector that collects into a TreeSet
      2. Writing a custom collector that collects into a LinkedHashSet
      3. Writing a custom collector that excludes elements of another collector
      4. Writing a custom collector that collects elements by type
      5. Writing a custom collector for SplayTree
    20. 203. Throwing checked exceptions from lambdas
    21. 204. Implementing distinctBy() for the Stream API
    22. 205. Writing a custom collector that takes/skips a given number of elements
    23. 206. Implementing a Function that takes five (or any other arbitrary number of) arguments
    24. 207. Implementing a Consumer that takes five (or any other arbitrary number of) arguments
    25. 208. Partially applying a Function
    26. Summary
  11. Concurrency – Virtual Threads and Structured Concurrency
    1. Problems
    2. 209. Explaining concurrency vs. parallelism
    3. 210. Introducing structured concurrency
    4. 211. Introducing virtual threads
      1. What’s the problem with platform (OS) threads?
      2. What are virtual threads?
        1. Creating a virtual thread
        2. How many virtual threads we can start
        3. Backward compatibility
        4. Avoiding fake conclusions (potentially myths)
    5. 212. Using the ExecutorService for virtual threads
    6. 213. Explaining how virtual threads work
      1. Capturing virtual threads
      2. Pinning virtual threads
    7. 214. Hooking virtual threads and sync code
    8. 215. Exemplifying thread context switching
      1. Example 1
      2. Example 2
      3. Example 3
    9. 216. Introducing the ExecutorService invoke all/any for virtual threads – part 1
      1. Working with invokeAll()
      2. Working with invokeAny()
    10. 217. Introducing the ExecutorService invoke all/any for virtual threads – part 2
    11. 218. Hooking task state
    12. 219. Combining newVirtualThreadPerTaskExecutor() and streams
    13. 220. Introducing a scope object (StructuredTaskScope)
      1. ExecutorService vs. StructuredTaskScope
    14. 221. Introducing ShutdownOnSuccess
    15. 222. Introducing ShutdownOnFailure
    16. 223. Combining StructuredTaskScope and streams
    17. 224. Observing and monitoring virtual threads
      1. Using JFR
      2. Using Java Management Extensions (JMX)
      3. Running 10,000 tasks via the cached thread pool executor
      4. Running 10,000 tasks via the fixed thread pool executor
      5. Running 10,000 tasks via the virtual thread per task executor
    18. Summary
  12. Concurrency ‒ Virtual Threads and Structured Concurrency: Diving Deeper
    1. Problems
    2. 225. Tackling continuations
      1. Introducing continuations
      2. Continuations and virtual threads
    3. 226. Tracing virtual thread states and transitions
      1. NEW
      2. STARTED
      3. RUNNING
      4. PARKING
      5. PARKED/PINNED
      6. YIELDING
      7. RUNNABLE
      8. TERMINATED
    4. 227. Extending StructuredTaskScope
    5. 228. Assembling StructuredTaskScope
    6. 229. Assembling StructuredTaskScope instances with timeout
    7. 230. Hooking ThreadLocal and virtual threads
    8. 231. Hooking ScopedValue and virtual threads
      1. Thread-local variables’ shortcomings
      2. Introducing scoped values
    9. 232. Using ScopedValue and executor services
    10. 233. Chaining and rebinding scoped values
      1. Changing scoped values
      2. Rebinding scoped values
    11. 234. Using ScopedValue and StructuredTaskScope
    12. 235. Using Semaphore instead of Executor
    13. 236. Avoiding pinning via locking
    14. 237. Solving the producer-consumer problem via virtual threads
    15. 238. Solving the producer-consumer problem via virtual threads (fixed via Semaphore)
    16. 239. Solving the producer-consumer problem via virtual threads (increase/decrease consumers)
    17. 240. Implementing an HTTP web server on top of virtual threads
    18. 241. Hooking CompletableFuture and virtual threads
    19. 242. Signaling virtual threads via wait() and notify()
    20. Summary
  13. Garbage Collectors and Dynamic CDS Archives
    1. Problems
    2. 243. Hooking the garbage collector goal
    3. 244. Handling the garbage collector stages
    4. 245. Covering some garbage collector terminology
      1. Epoch
      2. Single and multiple passes
      3. Serial and parallel
      4. Stop-the-World (STW) and concurrent
      5. Live set
      6. Allocation rate
      7. NUMA
      8. Region-based
      9. Generational garbage collection
    5. 246. Tracing the generational GC process
    6. 247. Choosing the correct garbage collector
    7. 248. Categorizing garbage collectors
      1. Serial garbage collector
      2. Parallel garbage collector
      3. Garbage-First (G1) collector
      4. Z Garbage Collector (ZGC)
      5. Shenandoah Garbage Collector
      6. Concurrent Mark Sweep (CMS) collector (deprecated)
    8. 249. Introducing G1
      1. Design principles
    9. 250. Tackling G1 throughput improvements
      1. Delaying the start of the Old generation
      2. Focusing on easy pickings
      3. Improving NUMA-aware memory allocation
      4. Parallelized full-heap collections
      5. Other improvements
    10. 251. Tackling G1 latency improvements
      1. Merge parallel phases into a larger one
      2. Reduction of metadata
      3. Better work balancing
      4. Better parallelization
      5. Better reference scanning
      6. Other improvements
    11. 252. Tackling G1 footprint improvements
      1. Maintain only the needed metadata
      2. Release memory
    12. 253. Introducing ZGC
      1. ZGC is concurrent
      2. ZGC and colored pointers
      3. ZGC and load barriers
      4. ZGC is region-based
    13. 254. Monitoring garbage collectors
    14. 255. Logging garbage collectors
    15. 256. Tuning garbage collectors
      1. How to tune
      2. Tuning the serial garbage collector
      3. Tunning the parallel garbage collector
      4. Tuning the G1 garbage collector
      5. Tuning Z Garbage Collector
      6. Tuning Metaspace (Metadata space)
    16. 257. Introducing Application Class Data Sharing (AppCDS, or Java’s Startup Booster)
      1. Tackling a JDK class data archive
        1. JDK 10/JDK 11
        2. JDK 12+
      2. Tackling application class data archive
        1. Before JDK 13
        2. JDK 13+
        3. JDK 19+
    17. Summary
  14. Socket API and Simple Web Server
    1. Problems
    2. 258. Introducing socket basics
    3. 259. Introducing TCP server/client applications
      1. Blocking vs. non-blocking mechanisms
    4. 260. Introducing the Java Socket API
      1. Introducing NetworkChannel
        1. Tackling socket options
    5. 261. Writing a blocking TCP server/client application
      1. Writing a single-thread blocking TCP echo server
        1. Creating a new server socket channel
        2. Configuring the blocking mechanism
        3. Setting server socket channel options
        4. Binding the server socket channel
        5. Accepting connections
        6. Transmitting data over a connection
        7. Closing the channel
        8. Putting it all together into the echo server
      2. Writing a single-thread blocking TCP client
        1. Creating a new (client) socket channel
        2. Configuring the blocking mechanism
        3. Setting client socket channel options
        4. Connecting the client socket channel
        5. Transmitting data over a connection
        6. Closing the channel
        7. Putting it all together into the client
      3. Testing the blocking echo application
    6. 262. Writing a non-blocking TCP server/client application
      1. Using the SelectionKey class
      2. Using the Selector methods
      3. Writing the non-blocking server
      4. Writing the non-blocking client
      5. Testing the non-blocking echo application
    7. 263. Writing UDP server/client applications
      1. Writing a single-thread blocking UDP echo server
        1. Creating a server datagram-oriented socket channel
        2. Setting datagram-oriented socket channel options
        3. Binding the server datagram-oriented socket channel
        4. Transmitting data packets
        5. Closing the channel
        6. Putting it all together into the client
      2. Writing a connectionless UDP client
      3. Testing the UDP connectionless echo application
      4. Writing a connected UDP client
    8. 264. Introducing multicasting
      1. A brief overview of MembershipKey
    9. 265. Exploring network interfaces
    10. 266. Writing a UDP multicast server/client application
      1. Writing a UDP multicast server
      2. Writing a UDP multicast client
      3. Blocking/unblocking datagrams
      4. Testing the multicasting server/client application
    11. 267. Adding KEM to a TCP server/client application
      1. Generating a public-private keypair by the receiver
      2. Transmitting the public key to the sender
      3. Generating the common secret key by the sender
      4. Sending the encapsulation message to the receiver
      5. Using the secret key to encrypt/decrypt messages
    12. 268. Reimplementing the legacy Socket API
    13. 269. Quick overview of SWS
      1. Key abstractions of SWS
    14. 270. Exploring the SWS command-line tool
      1. Starting SWS from the command line
      2. Configuring SWS from the command line
      3. Stopping SWS from the command line
    15. 271. Introducing the com.sun.net.httpserver API
      1. Using a custom HttpHandler
      2. Using a custom filter
      3. Using a custom executor
    16. 272. Adapting request/exchange
    17. 273. Complementing a conditional HttpHandler with another handler
    18. 274. Implementing SWS for an in-memory file system
    19. 275. Implementing SWS for a zip file system
    20. 276. Implementing SWS for a Java runtime directory
    21. Summary
  15. Other Books You May Enjoy
  16. Index

Product information

  • Title: Java Coding Problems - Second Edition
  • Author(s): Anghel Leonard
  • Release date: March 2024
  • Publisher(s): Packt Publishing
  • ISBN: 9781837633944