100% found this document useful (10 votes)
21 views

Download Full (Ebook) Java Coding Problems, 2nd Edition: Become an expert Java programmer by solving over 200 brand-new, modern, real-world problems by Anghel Leonard PDF All Chapters

The document promotes the ebook 'Java Coding Problems, 2nd Edition' by Anghel Leonard, which contains over 200 modern programming problems designed to enhance Java programming skills. It includes information about the author, contributors, and various topics covered in the book, such as text blocks, objects, date and time handling, and records. The ebook is available for download in multiple formats from ebooknice.com.

Uploaded by

breijozdzi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (10 votes)
21 views

Download Full (Ebook) Java Coding Problems, 2nd Edition: Become an expert Java programmer by solving over 200 brand-new, modern, real-world problems by Anghel Leonard PDF All Chapters

The document promotes the ebook 'Java Coding Problems, 2nd Edition' by Anghel Leonard, which contains over 200 modern programming problems designed to enhance Java programming skills. It includes information about the author, contributors, and various topics covered in the book, such as text blocks, objects, date and time handling, and records. The ebook is available for download in multiple formats from ebooknice.com.

Uploaded by

breijozdzi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Download Full Version ebook - Visit ebooknice.

com

(Ebook) Java Coding Problems, 2nd Edition: Become


an expert Java programmer by solving over 200
brand-new, modern, real-world problems by Anghel
Leonard
https://ebooknice.com/product/java-coding-problems-2nd-
edition-become-an-expert-java-programmer-by-solving-
over-200-brand-new-modern-real-world-problems-56236230

Click the button below to download

DOWLOAD EBOOK

Discover More Ebook - Explore Now at ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Java Coding Problems: Become an expert Java


programmer by solving over 200 brand-new, modern, real-
world problems, 2nd edition by Anghel Leonard ISBN
9781837633944, 1837633940
https://ebooknice.com/product/java-coding-problems-become-an-expert-
java-programmer-by-solving-over-200-brand-new-modern-real-world-
problems-2nd-edition-56220938
ebooknice.com

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;


Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena


Alfredsson, Hans Heikne, Sanna Bodemyr ISBN 9789127456600,
9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com

(Ebook) Cambridge IGCSE and O Level History Workbook 2C -


Depth Study: the United States, 1919-41 2nd Edition by
Benjamin Harrison ISBN 9781398375147, 9781398375048,
1398375144, 1398375047
https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044

ebooknice.com
(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT
II Success) by Peterson's ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018

ebooknice.com

(Ebook) Pro Java 7 NIO.2 by Anghel Leonard ISBN


9781430240129, 1430240121

https://ebooknice.com/product/pro-java-7-nio-2-36180254

ebooknice.com

(Ebook) Learning Java: An Introduction to Real-World


Programming with Java by Marc Loy, Patrick Niemeyer,
Daniel Leuck
https://ebooknice.com/product/learning-java-an-introduction-to-real-
world-programming-with-java-10865874

ebooknice.com

(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master


the SAT Subject Test: Math Levels 1 & 2) by Arco ISBN
9780768923049, 0768923042
https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-
arco-master-the-sat-subject-test-math-levels-1-2-2326094

ebooknice.com

(Ebook) Java Structures: Data Structures in Java for the


Principled Programmer (2nd edition) by Duane Bailey ISBN
9780072399097, 9780071121637, 9780071261203, 0072399090,
0071121633, 0071261206
https://ebooknice.com/product/java-structures-data-structures-in-java-
for-the-principled-programmer-2nd-edition-2541116

ebooknice.com
Java Coding Problems
Second Edition

Become an expert Java programmer by


solving over 200 brand-new, modern, real-
world problems

Anghel Leonard

BIRMINGHAM—MUMBAI
Java Coding Problems

Second Edition

Copyright © 2024 Packt Publishing


All rights reserved. No part of this book may be reproduced, stored in a
retrieval system, or transmitted in any form or by any means, without the
prior written permission of the publisher, except in the case of brief
quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the
accuracy of the information presented. However, the information contained
in this book is sold without warranty, either express or implied. Neither the
author, nor Packt Publishing or its dealers and distributors, will be held
liable for any damages caused or alleged to have been caused directly or
indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all
of the companies and products mentioned in this book by the appropriate
use of capitals. However, Packt Publishing cannot guarantee the accuracy of
this information.

Senior Publishing Product Manager: Denim Pinto

Acquisition Editor – Peer Reviews: Gaurav Gavas

Project Editor: Namrata Katare

Senior Development Editor: Elliot Dallow

Copy Editor: Safis Editing


Technical Editor: Aniket Shetty

Proofreader: Safis Editing

Indexer: Rekha Nair

Presentation Designer: Ajay Patule

Developer Relations Marketing Executive: Vipanshu Parashar

First published: September 2019

Second edition: March 2024

Production reference: 1120324

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-83763-394-4

www.packt.com
Contributors

About the author


Anghel Leonard is a chief technology strategist with more than 20 years of
experience in the Java ecosystem. In his daily work, he is focused on
architecting and developing Java distributed applications that empower
robust architectures, clean code, and high performance. He is passionate
about coaching, mentoring, and technical leadership.

He is the author of several books and videos and dozens of articles related
to Java technologies.
About the reviewers
George Adams is a senior software engineer at Microsoft and the Java
Champion and steering committee chair at Eclipse Adoptium. He was a co-
founder of AdoptOpenJDK in 2016 and, since then, has led its community
outreach efforts. He was instrumental in moving the project to the Eclipse
Foundation. George also contributes to both the Homebrew project and the
Node.js Foundation, where he is a core collaborator and plays an active role
in several of the workgroups.

Ivar Grimstad is a Jakarta EE developer advocate at the Eclipse


Foundation. He is a Java Champion and JUG Leader based in Sweden. He
contributes to the Jakarta EE specifications and is the PMC Lead for
Eclipse Enterprise for Java (EE4J). He is also a specification lead for
Jakarta MVC and represents the Eclipse Foundation on the JCP Executive
Committee. Ivar is also involved in a wide range of open-source projects
and communities and is a frequent speaker at international developer
conferences.
Join our community on Discord
Join our community’s Discord space for discussions with the author and
other readers:

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

The super-fast evolution of the JDK between versions 12 and 21 means two
things: first, Java now has a host of powerful new features that you can
adopt to solve a variety of modern-day problems; second, the learning curve
of modern Java is becoming very steep.
This book enables you to take an objective approach to solving common
problems by explaining the correct practices and decisions you need to
make with respect to complexity, performance, readability, and more.
Java Coding Problems, Second Edition, will help you complete your daily
tasks and meet deadlines, all while becoming a more proficient and self-
sufficient Java developer. You can count on the 270+ (all brand-new for this
edition) problems in this book to cover the most common and fundamental
areas of interest: strings, numbers, arrays, collections, the Foreign Function
and Memory API, data structures, date and time, pattern matching,
sealed/hidden classes, functional programming, virtual threads, Structured
Concurrency, Garbage Collectors, Dynamic CDS Archives, the Socket API,
and Simple Web Server.

Put your skills on steroids with problems that have been carefully crafted to
highlight and teach the core knowledge needed for daily work. In other
words (no matter if your task is simple, middling, or complex), having this
knowledge in your tool belt is a must, not an option.

By the end of this book, you will have gained a strong understanding of
Java concepts, and you’ll have the confidence to develop and choose the
right solutions to all your Java problems.

While this book is entirely stand-alone, and you do not need anything else
to get the most out of it, many of the topics covered in this book are also
explored in Java Coding Problems, First Edition. If you haven’t already
read it, and you wish to get even more practice in, then consider picking
that book up for a completely different set of Java problems.
Who this book is for
Java Coding Problems, Second Edition, is especially useful for late-
beginner-to-intermediate Java developers looking to level-up their
knowledge by solving real-world problems. However, the problems looked
at within these pages will be encountered in the daily work of any Java
developer, from beginner all the way to advanced practitioner.

Therefore, it is recommended that you are familiar with the Java


fundamentals and have at least a foundational working knowledge of the
language.
Random documents with unrelated
content Scribd suggests to you:
In our last paper we endeavoured to show that his Lordship could
not have acted otherwise than he has done. A contemporary of
yesterday has reviewed the remarks we then made. After affecting
to consider them as coming from a “higher quarter” than ourselves,
in order, of course—to secure the greater attention to his own
observations—he still contends that the Lord Advocate acted
improperly in giving immunity to Hare and his wife, and that if he
had not done so, he might have accomplished the conviction of more
of the gang than Burke. On a prima facie consideration of the
subject, this must appear very unlikely. His lordship was, of course,
in possession of all the evidence in its authentic shape, the broken
parts of which have been wafted, in an exaggerated form, to the
knowledge of the public. He was, perhaps, aware too, that the
murders had all been so committed as to preclude the chance of
direct evidence of them, except either from Burke or Hare—who
were accustomed, according to the recent confession of Burke, to
keep even their wives out of the way, on such occasions. Our
contemporary has not stated, and we, therefore, imagine, cannot
state, that any third party, not of the gang, ever witnessed a single
one of the murders, or was ever so connected with their
perpetration, as to be able to give any thing approaching to the
requisite direct evidence on the subject. He should be prepared to
do so, however, before censuring the Lord Advocate for a mode of
procedure which may have been, and which, we believe, was wholly
unavoidable.
Our contemporary objects to the extent of immunity he supposes
to have been given to Hare and his wife. On this point, we should
think, he need feel no uneasiness. If king’s evidence was necessary
—if without such evidence it be plain from what has occurred on the
trial of Burke, that there was more than a chance, a probability
even, that the conviction of none of the gang could have been
obtained—we may rest assured that the Lord Advocate offered no
farther premium on the treachery which he felt to be requisite, for
the sacrifice of some of them, than was absolutely necessary to
insure it.
But then our contemporary thinks that, at all events, a different
selection ought to have been made, and that, by the testimony of
M‘Dougal, had she been admitted as king’s evidence, Hare might
have been convicted as well as Burke. In our last paper, we stated
that M‘Dougal, although not actually married to Burke, had, for ten
years, lived with him as his wife, and, in law, therefore, was so, and
could not be examined against him; and as the other woman could
not, for the same reason, have been examined against Hare—and
neither of them could furnish against the husband of the other, that
clear and decisive evidence required from socii criminis, to give it
sufficient weight; the result of taking them as king’s evidence might,
and probably would have been, the escape of the whole four. Burke,
however, it seems, has been confessing since his condemnation,
and, as one of his confessions is said to lead to an inference that his
cohabitation with M‘Dougal could not make her his wife, as either he
or she were previously married, and the wife or husband of the
former marriage still alive—our contemporary, on the tacit
assumption that this even yet mysteriously hinted at fact was or
ought to have been known, and capable of proof before the trial—
endeavours to give the coup de grace to our argument against the
possibility of having made M‘Dougal give evidence against Burke. His
attempt to do so is founded on the result of what is generally called,
reasoning in a circle, and seems to require no farther notice. His
whole argument, indeed, on this part of the subject proceeds on this
other assumption, that the Prosecutor, in looking out for king’s
evidence, has the selection of it entirely in his own hand. This, we
rather think, is but seldom the case; and, where the gang have been
connected as husbands and wives, the selection must often be
prescribed to him, or made imperative, by circumstances over which
he can have no control. Is our contemporary quite sure that the Lord
Advocate had not his hands tied, in this way, in the present case?
As to his lengthened argument to show that had the Lord
Advocate not moved for judgment against Burke, when found guilty
of the last of the three murders charged against him, it would have
been competent to have led evidence of the circumstances attending
the other two—we would simply ask, cui bono? What good effect
could have resulted from the leading of it? Hare and his wife being
protected as king’s evidence against the consequences of their
participation in them, and M‘Dougal not being charged with them at
all, they could only have been proved against Burke. After what had
passed, must not this have seemed, in so far as Burke was
concerned, to be like the pouring of water on a drowned mouse,
and, in so far as the public was interested, to be the exciting of
feeling unnecessarily and without object?
Our contemporary, in conclusion, asserts, that whatever immunity
the Lord Advocate may have felt it necessary to give to the infamous
Hare, the mother of “Daft Jamie,” taking advantage of the
disclosures made by that wretch under promise of pardon, is entitled
to prosecute him, with the concurrence of the Lord Advocate, which
concurrence, in all these circumstances, his Lordship, he says, will be
bound to give. This seems very novel doctrine. We can only say, that
we should be extremely glad to think our contemporary correct in
laying it down; and no man, we are certain, would be more happy to
think his reasoning without flaw, than the Lord Advocate.
There is still another point of dittay against his Lordship, an
insinuation that he is unwilling to prosecute trains to the knowledge
of other murders which are said to have opened to him, and which
are reported to implicate other murderers than those already known
to the public. Such an insinuation might safely be contemned by any
one, and must be far too incredible, when made against his
Lordship, to find a couple of ears on the respective sides of the most
credulous head in the strongholds of credulity itself, to take it in. The
Lord Advocate, we suppose, thinks coolly before he acts—finds out
some person to be tried—and on grounds inferring probable
conviction, before he institutes the trial; and, as our contemporary
admits that he is still proceeding in his investigations, the charge of
unwillingness to prosecute, seems, even on his own showing, to be
very premature, as well as incredible.
We are satisfied that, in the prosecution of Burke and his
associates, and in the investigation of the system of murder with
which they have been connected, the Lord Advocate has done, and
is doing his duty, ably, impartially, and fearlessly, and that he is
entitled to the highest praise instead of the slightest censure. Feeling
this to be the case, we cannot withhold our humble effort to make it
appear so.

Edinburgh Observer.
The people are not satisfied with the imperfect disclosures that
have taken place, and the trivial atonement that is to be made to
outraged humanity, by the death of only one of the atrocious gang.
There is a cry for blood—more blood—throughout the land; and
coming, as it does, from the bulk of the nation, it will require no little
discrimination and firmness, on the part of the Public Prosecutor, to
see his way clearly, and to keep it when he has found it. A more
difficult situation than his, at the present time, we cannot well
imagine. Even the activity of the press, in reiterating the calls for
further inquiry and for more victims, at the very moment when he is
known to be indefatigably employed in prosecuting the one and
searching for the other, has greatly contributed to render his duties
more harassing and ungracious. Under a sincere, and, despite what
others say, we conceive a just impression, that all the monsters
might escape the gallows, as one of them has actually done, by a
verdict of “not proven,” he permitted two of them to purchase their
worthless lives by bearing testimony against their associates. That
the Hares obtained this immunity as being the lesser criminals in his
estimation, we do not believe. The fact of the particular murder,
which led to the whole discoveries, having been perpetrated under
Burke’s roof, naturally pointed out him and his guilty partner as the
more immediate objects of legal vengeance. It is evident, that
throughout the whole business, the Lord Advocate has been
actuated by the most honourable anxiety to investigate the affair to
the uttermost; and had he not, at the very outset of the trial, been
urged into a concession to the legal scruples of the counsel opposed
to him, whose eloquence most assuredly reft one wretch from the
clutch of the hangman, not merely one, but three acts of the horrid
drama would have been publicly revealed. It is stated, that since the
trial, his Lordship and his assistants have been unremitting in their
inquiries. He has attended almost every precognition, and surveyed
in person the foul abodes which the murderers inhabited, and even
the dwellings of their victims. But he refuses to violate the public
faith, of which, in this instance he is the custodier, by yielding up the
tools he has been forced to employ, to that punishment which they
have so abundantly merited, yet from which the nation stands
pledged they are redeemed. God forbid that we should advocate the
indemnity of these monsters on any ground, save the sanctity of
such a pledge. We question greatly, whether Hare and his partner,
cast upon the world with ignominy and crime branded on their
foreheads, are not more condignly punished, than the wretched man
whose days are numbered, and whose doom, it is certainly not
uncharitable to predict, will yet overtake them. In the case of
Weare’s murder, Probert, one of the accessaries, was admitted to a
like immunity. When his foul breath had consigned one of his
associates to the gallows, he was allowed to go forth into the world
a free man; but, like Cain, he found himself an outcast, and, in the
course of a few months, was again arraigned as a felon, convicted,
and executed.
Though we dissent from the summary mode of procedure which
many people recommend, and conceive that it would be a perilous
innovation on the prerogative of the Public Prosecutor to say, that in
this instance, his pledge of immunity shall be disregarded, unless
some new charge can be substantiated, we view the detestation so
unaffectedly expressed by the public towards the whole gang, as
consolatory to humanity. Had criminals, with hands so deeply dyed
in blood, found even one commiserator or advocate beyond the
walls of the Court of Justice—had any man ventured to whisper that
the crimes which they have perpetrated are not worthy of death—
nay, had not the whole nation lifted up its voice, and declared, that
even death itself was but a miserable atonement for crimes so
monstrous, we should have regarded it as a national disgrace. It is
to be hoped, however, that this laudable spirit will not degenerate
into tumultuary violence. The authorities, we are satisfied, will not
relax their efforts to develope the whole of these sanguinary
atrocities; and, if the correspondence which is at present carrying on
between the Lord Advocate and the teachers of anatomy should, in
conjunction with other investigations in progress, lead to the
inculpation, in the remotest way, of any individual, we are satisfied
that nothing will shield the culprit from the vengeance of the law, be
his rank or previous respectability what it may. As yet only one
individual of that body has been in any way implicated in these
horrible transactions; and we know that a feeling is prevalent that he
has been treated with greater delicacy than he deserves; but the
culpability of one man must not be received as condemnatory
evidence against a whole tribe. An earnest desire is entertained by
the teachers of anatomy that the fullest investigation should take
place; and if criminal laxity in the receipt of subjects can be traced to
any particular quarter, an ample exposition will follow. This
exposition they are entitled to demand; for the reputation of the
whole fraternity is perilled by the revolting suspicions which the
crimes of their caterers have engendered.

The Caledonian Mercury.


THE PUBLIC PROSECUTOR AND HIS APOLOGISTS.
Mieux cents ennemis qu’un imprudent ami.—French Proverb.
The remarks which appeared in our Monday’s publication, on the
defence of the Lord Advocate inserted in a contemporary Journal of
Friday last, have been reviewed, not answered, in the columns of
the same paper of Tuesday; and were it not of the very greatest
importance, at the present moment, that the public should be
accurately informed respecting some of the points at issue, we
should have been well content to leave the subject to the decision of
all competent persons, upon our first and somewhat hurried
statement. We trust that we shall be excused for proceeding at once
to deal with the only matters of law and fact to which the writer has
thought proper to advert.
And, in the first place,—(for the sake of perspicuity, we shall take
the different topics in the same order as formerly)—the writer
reluctantly admits the validity of the argument which we adduced “to
show that had not the Lord Advocate moved for judgment against
Burke, when found guilty of the last of the three murders charged
against him, it would have been competent to have led evidence of
the circumstances attending the other two.” But he asks, cui bono?
“What good effect could have resulted from the leading of it?” We
answer, first, that it would have redeemed the Lord Advocate’s
pledge; and, secondly, that it would have satisfied the country. Both
in replying to the arguments of the prisoner’s Counsel on the
relevancy, and in addressing the Jury for the Crown, his Lordship
distinctly pledged himself to probe and sift the whole of these
murders to the bottom. In the former case, while contemplating
being under the necessity of deserting the diet against M‘Dougal,
owing to the view taken of the indictment by the Court as containing
a cumulatio actionum, and the exercise of their discretionary power
in separating the charges, he said, “The question is now reduced to
one of time and trouble; for if I do not proceed against her to-day,
she will be proceeded against ten days hence. In such circumstances
I shall not certainly insist now on that woman’s being tried on this
indictment. I shall proceed against her alone, since she now says
that being tried on this indictment will prejudice her case.” And
again, almost immediately after, he added, “No motive shall induce
me, for one moment, to listen to any attempt to smother this case;
to tie me down to try one single charge instead of all the three. I am
told that the mind of the public is excited; if so, are they not entitled
to know from the first to the last of this case; and is it not my duty
to go through the whole of these charges? I would be condemned
by the country if I did not, and what to me is worse I should deserve
it.” The Court, in giving judgment on the relevancy, fully recognised
the propriety of this most distinct and articulate pledge; for Lord
Pitmilly unequivocally held, that it was competent to try Burke on all
the three charges, and that the Public Prosecutor should proceed
with the first and then with the others. Lord Meadowbank, entirely
concurring in this view, expressed his opinion, that while their
Lordships sustained the indictment, they should “direct the Lord
Advocate to proceed separately in the trial of the different charges.”
Lord Mackenzie and the Lord Justice Clerk acquiesced in this
suggestion, and, in fact, it ultimately became the judgment of the
Court. Fortified by such authority, the Lord Advocate accordingly
reiterated his pledge in his address to the Jury, and in terms equally
emphatic and unequivocal. Now, we would simply ask the writer
before us, Was this sacred and solemn pledge redeemed? Were “all
the three” charges tried? Were they gone through from first to last?
Did the Prosecutor do his duty according to his own view of it, by
going “through the whole of these charges?” He cannot answer in
the affirmative. By moving for, and obtaining judgment against Burke
on the conviction under the first charge, he rendered it impossible
for himself to redeem his pledge; and two of the charges were, in
consequence, dismissed without investigation. Now, was this not an
error in judgment, which is all we ever alleged? Nay, was it not an
error calculated to place the Prosecutor in a very embarrassing
position in reference both to his own pledge and to the public? It is
true the apologist says that trying Burke upon the first and second
charges, after he had been convicted on the third, would have been
“like pouring water on a drowned mouse.” But we cannot say we
admire either the elegance or the felicity of this illustration. The
question is not one that concerned Burke, whose fate was in fact
determined by the conviction under the third charge. It concerned
the Lord Advocate and the country alone; the former as having
become bound to try “all the three” charges; and the latter as, by
his Lordship’s admission, “entitled to know them from first to last,”—
a knowledge which his Lordship conceived it to be his “duty” to
afford, and which he would be deservedly condemned by the
country if he did not afford. But the writer adds, that taking any
further proceedings was calculated “to excite the feelings of the
public unnecessarily and without object.” We are really surprised that
any person could have been found short-sighted and ignorant
enough to hazard such an assertion. What! was the exposure of one
murder, and the quashing of all investigation into the circumstances
of other two, calculated to allay the excitement of the public mind;
or rather, was it not calculated to produce the very opposite effect?
A corner of the veil only had been lifted up; a glimpse merely had
been given of crimes which this very writer himself describes as
“destined in point of atrocity, to stand alone, and in advance of every
other that man has hitherto been known to commit,” and as covering
up from the view “the very outposts and limits of human
wickedness;” and then the curtain was suffered to drop on others
which it was equally necessary that the public should know, and
which they were equally “entitled” to have fully and thoroughly
brought to light: this was the course pursued; ample scope was
given for the imagination to work, under the influence of an
undefined apprehension; and yet we are gravely told that this was
the most approved mode which could have been adopted to prevent
an unnecessary excitation of public feeling! Has it been attended, we
would ask, with any such results?
Next, as to the unquestionable title of Daft Jamie’s mother to
prosecute Hare for the murder of her son, with concourse of the
Lord Advocate, which concurrence his Lordship may be compelled to
give, our learned opponent remarks, that “this seems very novel
doctrine.” We certainly do not hold ourselves bound to instruct our
opponent in the first principles of criminal law; but, for the sake of a
public purpose, we shall endeavour to show that the doctrine we
maintain, so far from being “novel,” is tritissimi juris, one of the most
common and most thoroughly settled principles in our criminal code.
To entitle a private party to prosecute, he must have an interest, not
remote or feeble, but immediate and powerful in the cause; the
wrongs alleged must be wrongs done to the person, and “of a high
and aggravated kind, such as may naturally excite strong feelings of
anguish and resentment in the minds of the kindred of the sufferer;”
an oath of calumny must be taken by the prosecutor, if required by
the party accused; caution must be found to insist in the
prosecution; and the law also subjects the private prosecutor in
expenses, and even in penalties, if he insist in a groundless or
malicious accusation. Now has not the mother of Daft Jamie an
interest in the prosecution we point at? Was there not a wrong done
to the person of her innocent child who was foully murdered? May
she not with perfect safety take the oath de calumnia, if required?
And is it impossible for her to find caution to insist, and to find
means to defray the expense of the prosecution? The public, with
their usual generosity, will, we doubt not, give a practical answer to
the last of these queries; and as to the others, we profess ourselves
unable to discover that we have proponed any “novel doctrine.”
Again, we said the Lord Advocate might be compelled to grant his
concurrence in such circumstances; and we think Mr. Burnett and Mr.
Baron Hume will amply bear out our assertion. The former, after
stating at length the conditions above briefly indicated, says, it is
perfectly understood “that his Majesty’s Advocate cannot refuse his
concourse, and may be compelled to give it, in all cases where the
complaint of a private party is founded on a known and relevant
point of dittay, (murder for example) and as to which he has prima
facie a title to insist.” pp. 306–7.—And Mr. Baron Hume is, if possible,
still more explicit on the point. After stating that the Lord Advocate
may refuse his concourse, if it be asked to a charge of witchcraft,
which a statute has expunged from the list of crimes, or of treason
for which no private party can prosecute, or of murder at the
instance of some stranger, who does not even allege that he is
anywise related to the deceased, he goes on to say, “On the other
side, certainly the Lord Advocate is not the absolute and accountable
judge on such occasions; but is subject to the control and direction
of the Court, who will oblige him to produce and justify the grounds
of his refusal to concur. Nay more; except in such extraordinary
situations as those above supposed, he shall not even be allowed to
engage in any inquiry concerning the merits of the case, the
propriety of the prosecution, the form of the action, the sufficiency
of the title, or the like, but shall be ordained to comply straightway;
leaving the discussion of these matters for the proper place and
season, after the libel shall be in Court.” Vol. II. pp. 123–24. Lord
Alemore’s opinion, given on the complaint of Sir John Gordon against
his Majesty’s Advocate, June 21, 1706, is equally precise: “Had the
Advocate refused his concourse, he might have been compelled to
give it, for everyone is entitled to justice; but he cannot be forced to
prosecute.” Maclaurin, p. 298. Is there any “novel doctrine” in all
this?
But our opponent endeavours to complicate the matter by most
disingenuously attributing to us a statement which we never made,
or even so much as dreamt of, namely, that the mother of Daft
Jamie, “taking advantage of the disclosures made by the infamous
Hare, under promise of pardon,” is entitled to prosecute him with the
concurrence of the Lord Advocate. The artifice is paltry enough; but
our answer is, that the rights of the private party, who, as such, “is
entitled to justice,” cannot be in any manner of way læsed or
impaired, far less destroyed by any previous proceedings of the
Prosecutor, in his public capacity; especially when these proceedings
are in the eye of the law illegal, and only winked at upon a principle
of utility or general expediency. What, in the name of common
sense, of reason, and of law, had the mother of Daft Jamie to do
with the disclosures made by Hare to the Lord Advocate “under
promise of pardon?” That “promise” may be good against his
Lordship himself; but it is utterly monstrous to pretend that it can in
any way affect the rights of a private party who comes forward to
prosecute; which it would unquestionably do, in the most serious
manner, were his Lordship to be held entitled, in virtue of that most
injudicious promise, to refuse his concurrence. Nay, we maintain, on
the authority of Mr. Baron Hume, that it would be illegal in the Lord
Advocate, when his concourse was applied for, to take any such
circumstance into his consideration at all; for it is expressly laid
down in the passage already quoted, that his Lordship “shall not
even be allowed to engage in any inquiry concerning the merits of
the case; the propriety of the prosecution, the form of the action,
the sufficiency of the title, or the like; all these are jus tertii to him;”
and, accordingly, the Court would “ordain him to comply
straightway; leaving the discussion of these matters for the proper
place and season, after the libel shall be in Court.” This, we should
think, is not very “novel doctrine;” and as no man, we are assured,
“would be more happy to think our reasoning without flaw, than the
Lord Advocate,” (which we well believe,) we humbly hope that the
exposition we have now given will be found to answer that
condition.
These then are the main points of our case; and we flatter
ourselves that we have made them out. But as we are resolved to
engage in no further controversy on the subject, and therefore wish
to clear off our score at once, we shall take the liberty of adverting,
before we conclude, to one or two points of secondary importance,
on which our opponent strenuously insists.
And, in the first place, he persists in maintaining that “had Hare
and his wife not been witnesses, there is the best reason for
supposing that the conviction of none of the four would have been
obtained.” We would have been much better pleased, however, had
this incurious apologist condescended to inform us in what this “best
reason for supposing” consisted; as we confess our own inability to
discover a shadow of “reason” for the “supposition” so gratuitously
made. The point, we are well aware, is an important one for our
opponent; because, unless he can make out that there was no case
against Burke, without the evidence of Hare and his wife; in other
words, disprove our argument that there was sufficient testimony to
convict without the evidence of the accomplices at all, then our
conclusion is inevitable, that Hare and his wife ought to have been
at the bar, and not in the witness-box. But, strange to say, although
the point at issue is so important to the justification which our
adversary labours to make out, he has not ventured to bring forward
a single argument, or show a vestige of “reason” or authority, for the
opinion he so strenuously asserts. We shall not, however, follow his
example in this respect, but state as shortly as possible the grounds
upon which we hold that Hare and his wife ought to have been
placed at the bar beside Burke and M‘Dougal.
The testimony of a socius criminis is good in law only in so far as
it is corroborated by other testimony perfectly unexceptionable, or
by circumstances of real evidence; and where it stands alone and
unsupported, it is the duty of the presiding Judge to direct the Jury
to pay no attention whatever to it. Let us apply this test to the
evidence of Hare and his wife, and observe to what conclusion it will
lead. The former, wherever he spoke to circumstances which fell
within the knowledge of unexceptionable witnesses, differed from, or
rather was flatly contradicted by them; and consequently his
evidence in regard to these was of no avail whatever, except to
impeach his own credibility. Again, he was contradicted by his wife in
respect to several of the occurrences in Burke’s and Connaway’s on
the evening of the murder; and both were contradicted in regard to
other matters in which they agreed, by the unexceptionable
witnesses. As to what they said in regard to matters concerning
which no other person could speak, they stood alone and
unsupported, and of course were not in law entitled to be believed;
while they were farther discredited by the want of all corroboration
in regard to circumstances spoken to equally by them, and by the
unexceptionable witnesses. How then was it possible that any weight
whatever could be attached to such evidence, either by the Court or
the Jury, particularly the latter? Two miscreants, whose only title to
be believed was their having been engaged in the commission of
three murders, are adduced as witnesses to speak to one of them,
and wherever their testimony is susceptible of being corroborated, it
is flatly and pointedly contradicted by persons who are above all
suspicion; and where it stands alone and unsupported, it is in the
eye of the law worth nothing. Why, then, were such witnesses
adduced at all? They were not necessary, because their testimony
was not and could not be believed; and, in point of fact, their
depositions served no other purpose, except to enable the Dean of
Faculty to plead what would have been otherwise nearly an
unpleaded case, and to point out such a formidable array of flagrant
contradictions as to shake the minds of the Jury in regard to the
effect of the unchallenged and unchallengeable testimony. The case,
therefore, was, in point of fact, made out against Burke by other
evidence than that of Hare and his wife; and as the same evidence
which led to the conviction of Burke, would have also led to the
conviction of Hare at least, we have again to submit that that
hideous wretch, if not also his wife, ought to have been placed at
the bar beside his brother murderer.
We are accused of having blamed the Lord Advocate “for not
having possessed the gift of second-sight;” and various other follies
which seem to have entered the imagination of our opponent, when
heated with his subject, are also laid to our charge. To these,
however, we disdain to offer any reply. We can well believe that the
case opened upon his Lordship gradually, and that, had he now to
retrace his steps, he would, in many respects, act differently from
what he has done. With the very best intentions in the world, a
Prosecutor may be placed in such circumstances as almost inevitably
to lead him to bungle a case: but surely it can be no very heinous
offence to point out such errors as a warning for the future, and at
the same time to show how even at present they may be in a great
measure remedied.—“The very head and front of our offending hath
this extent—no more.” It is true, we called for further investigation,
and we did our best to indicate what channels ought to be explored.
That call has been answered, and inquiries have been set on foot
which can scarcely fail to lead to important results. In regard to the
nature of these inquiries, or the facts which have been elicited, we
are for the present dumb. Our object is to aid, not to thwart, the
progress of judicial investigation; and no wish to gratify the public
curiosity, or any other motive indeed shall induce us to breathe a
whisper calculated to defeat the great and necessary purpose which
the Public Prosecutor is now labouring so zealously to accomplish.
In order to give a connected account of the preliminary legal
proceedings respecting the contemplated trial of Hare, we shall
delay introducing the subject at present. In a future number a detail
of the whole proceedings will be given.
We now proceed to detail the particulars which we have carefully
collected, with respect to the lives and characters of the several
individuals who have been concerned in these nefarious
transactions. Of these, the first we shall notice is,

WILLIAM BURKE.

We can pledge ourselves that every circumstance that is here


narrated, has been obtained from such sources as to leave no doubt
of its authenticity; it will be seen that while this memoir is a great
deal fuller than any one that has appeared, it is also dissimilar, in
many particulars, to the disjointed fragments that have been from
time to time published; how these have been obtained, we cannot
say, but we can aver that this account has been received from
sources which may be relied on, and much of it from the unhappy
man himself, indeed so much as to entitle us to say that it is almost
his own account.
William Burke, whose crimes have condemned him to an
ignominious death on the scaffold, describes himself, in his judicial
declaration, emitted before the Sheriff-substitute of Edinburghshire,
in relation to the cause for which he was tried, as being thirty-six
years of age. He was born in the parish of Orrey, near Strabane,
county of Tyrone, in Ireland, about the year 1792. His parents were
poor, but industrious and respectable in their station, which was that
of cottiers, occupying, like the most of the peasantry of Ireland, a
small piece of ground. The Irish are remarkable for the avidity with
which they seek education for their children, under circumstances in
which it is not easily attainable. The parents of Burke seem to have
been actuated by this laudable desire, as both William and his
brother Constantine, must have received the elements of what, in
their condition, may be called a good education, and superior to
what usually falls to the lot of children in their rank in Ireland. He
was educated in the Roman Catholic faith, which he has ever since
nominally adhered to, though with little observance of its doctrines
or ceremonies. He is by no means, however, a person of the brutal
ignorance or stupid indifference that his callously continuing in a
course of unparalleled wickedness, apparently without compunction,
would betoken. He has sinned deeply, but it has not been altogether
against knowledge, as he could at times put on a semblance of
devotion; and during the fits of hypocrisy, or it may be, starts of
better feeling, before he became so miserably depraved, his
conversation was that of a man by no means ignorant of the truths
of Christianity, and such even as to lead some to imagine him
seriously concerned about his eternal salvation. During one of these
temporary ebullitions about five years ago, he became an attendant
on a prayer-meeting held on the Sabbath evenings in the
Grassmarket. He was, for some time, remarked as one of its most
regular and intelligent members. He never omitted one of its
meetings, and expressed much regret when it was discontinued. As
a Catholic, he was considered wonderfully free from prejudice,
frankly entering into discussions upon the doctrines of his church, or
those of other sects, with whose tenets he showed some
acquaintance.
He read the Scriptures, particularly the New Testament, and other
religious books, and discussed their merits. On a Sabbath, especially
though he never attended a place of worship, he was seldom to be
seen without a Bible, or some book of devotion in his hands.
At that time no one of his acquaintances would have admitted the
idea for a moment that he was capable of committing such infamous
crimes, and probably his own mind would have revolted at the
contemplation of such enormities; but a continued indulgence in sin
produced in him its never failing consequences in hardening and
deadening the heart, and fitting it for the perpetration of deeds,
which a little before the sinner would have shuddered at.
Burke was remarked to be of a very social and agreeable
disposition, with a great turn for raillery and jocularity, and what
from his after proceedings could scarcely have been supposed, was
distinguished not only as a man of peculiarly quiet and inoffensive
manners, but even as evincing a great degree of humanity. Of this
softness of heart, a singular instance is given by an acquaintance
and near neighbour, whose child Burke was remarkably fond of, and
used to caress much. The little boy chanced, during the time he
lodged in the neighbourhood, to be afflicted with a tumour and
gathering on the neck, and his mother took him to a neighbouring
dispensary. The medical attendants there considered it advisable to
open the gathering, which was done. Upon the mother’s return
home with the child, she informed Burke of what had taken place;
he appeared very much affected at the recital, and said repeatedly
that he could not have witnessed the operation; that the mention of
it made his flesh creep, and expressed great surprise that the
mother could be so cruel as to permit and witness it.
At an after period, in Peebles, he still made considerable
pretensions to religion, as the subjoined note testifies.[3] It is from
an intelligent correspondent of the Saturday Evening Post, who
mentions, “On my first visit to his house, he had one or two religious
books lying near him, which he said he read; being at that time
confined by a sore leg.” Somewhat inconsistent with this pretended
sanctity, is the other part of the intelligence, that, “on Saturday
nights, and the Sabbath days, his house was the scene of riot and
drunkenness with the lowest of his countrymen.” In his confessions,
published in the Caledonian Mercury, the following testimony, borne
by himself, as to his religious feelings, appears:
“He states, that while in Ireland, his mind was under the influence
of religious impressions, and that he was accustomed to read his
catechism, and his prayer-book, and to attend to his duties.”
All his pretensions, however, seem to have had but little influence
on his life and conversation, as he was all the time living in the
flagrant violation of the plainest dictates of religion, a drunkard,
blasphemer, and adulterer.
Burke originally worked as a labourer about his native place,
assisting his father, and living in his house, until he attained the age
of eighteen, when he left him. He then went as servant to a
gentleman in the neighbourhood, but after being one year in this
capacity, the gentleman died, when he was obliged to seek other
employment.
At the age of nineteen, he entered the Donegal militia as a
substitute, and served in it as a private soldier for seven years. In
this regiment, his brother Constantine held the rank of a non-
commissioned officer. During the greater part of his service, he acted
in the capacity of an officer’s servant; and from the propriety with
which he acquitted himself, gained considerable respect.
It was at this period that he became acquainted with a young
woman, of a respectable character, in Ballina, county of Mayo, to
whom, after some time, he was regularly married. By her, he had
seven children, of whom some were still-born. All of them, excepting
one boy, are now dead. His wife still survives, and resides with her
father in Ireland.
It is probable, that notwithstanding her good character, the
connection was not a very comfortable one for her. He proved
unfaithful to her; and this is a vice which must have marred their
domestic happiness. Indeed, even at his best time, he appears to
have displayed considerable laxity in his intercourse with women.
At the general peace, his regiment was disbanded, along with the
rest of the militia forces. He then went with his family to reside in
the county Mayo, in the neighbourhood of his father-in-law. He was
also in the same class as Burke’s parents, and possessed a small
farm, which, in conformity with the custom in Ireland, he was willing
to parcel out to his family and connections. The system pursued in
that country, of the lessee or tacksman, of what originally is,
perhaps, a very small farm, sub-leasing miserable portions of it to an
indefinite number of retainers, is now so universally understood, that
it is unnecessary here to explain it. In a country swarming with an
unemployed population, and when so many additional claimants for
the most wretched patch of potatoe ground, had been superadded
by the reduction of the army, to the already redundant population, it
must have been no slight good fortune in Burke, to find a father-in-
law whose farm could still afford sustenance for another family. He
does not seem, however, to have been contented with the
permission that was allowed him to cultivate, from year to year, for
his own behoof, the share that was allotted to his use, and insisted
upon having a lease granted him. This the old man peremptorily
refused, on the allegation, that his object, after obtaining the lease,
was to sell it and desert his family. This difference led to squabbling
between them; and after it had continued for some time, Burke
finding that there was no probability of gaining his point, abandoned
the project, and deserted his wife and family.
After taking leave of his parents, he came to Scotland in 1817 or
1818. He then engaged as a labourer, on the cutting of the Union
Canal, soon after its commencement; and subsequently wrote to his
wife in Ireland, but she would not receive the letter. After some time
it was returned to him, and with this, all intercourse with his family
ceased, never to be renewed. He has ever since, however, spoken in
respectful terms of his wife, and several times expressed an
intention, when he could get matters arranged, of returning to her;
but motives are seldom wanting, for a continued indulgence in a
favourite sin, and want of clothes, to make a respectable
appearance, when he joined her, or some other frivolous pretence,
constantly diverted him from his purpose.
While employed upon the Union Canal, he accidentally met the
woman M‘Dougal at the village of Middiston in Stirlingshire, where
she was residing with her father after the death of her husband. The
story told of his falling in with her on the streets of Glasgow is
incorrect. An intimacy was speedily formed, and about a year from
the commencement of their correspondence, they agreed to live as
man and wife, and have done so ever since.
A similarity of disposition seems to have produced a
corresponding affection, and the sympathy that attracted them to
each other appears still to have outlived all their quarrels and the ill
usage he subjected her to. They have expressed great attachment to
each other since his conviction. It is understood that an account of
his connection with M‘Dougal, while his wife was still alive, having
been made to the priest of his religion, he was first admonished, and
recommended to return to her, and upon his refusal to do so, was
excommunicated. This may perhaps in some measure explain his not
attending chapel while his religious fits were upon him.
He, after the completion of the canal, came, along with M‘Dougal,
to reside in Edinburgh, and engaged in the petty trafficking in
various sorts of merchandise practised by many of his countrymen,
travelling about the country in prosecution of his trade. He dealt in
different sorts of pedlary wares, old clothes, &c. and collected skins,
human hair, &c. in the country.
During the work on the canal, he had been noted among the
other labourers as of a particularly handy active turn, and skilful in
cobbling, in a rude way, his own and the shoes of his acquaintances.
After his subsequent settlement in Edinburgh, he turned his talent to
some account; and though he never had learned the craft and
mystery of shoemaking, contrived to gain from fifteen to twenty
shillings a week by his new acquirement. His practice was to
purchase quantities of old shoes, and, after cobbling them in the
best fashion he could, to send M‘Dougal to hawk them about among
the colliers and poor people of her native district.
At this time he lodged in the house of an Irishman named
Michael, or more commonly Mikey Culzean, in the West Port, who
kept a lodging-house for beggars and vagrants, similar to the one
which Hare’s crime has made so familiar to the public,—in the
language of the classes who frequent them,—a beggars’ Hotel.
Many will probably recollect of a fire happening in one of these
abodes of wretchedness about six years ago, when incredible
numbers emerged from the miserable hovels. In this conflagration
Mikey’s dwelling suffered, and Burke and M‘Dougal escaped from the
flames nearly naked, and with the loss of all the little property they
possessed. Some charitable individuals contributed to procure
clothes and necessaries for the sufferers, and they received some
relief by the hands of the Rev. Dr. Dickson, one of the ministers of
the parish. By this disaster he lost his library; and though it is
somewhat surprising to hear at all of a collection of books under
such circumstances, it is not the less so when the names of some of
the works are mentioned. Among them were, Ambrose’s Looking
unto Jesus, Boston’s Human Nature in its Fourfold State, the
Pilgrim’s Progress, and Booth’s Reign of Grace. His landlord
afterwards took a room in Brown’s Close, Grassmarket, where Burke
also again went as a lodger.
It was at this time that he attended the religious meeting we have
previously mentioned, which was held in the next apartment to the
one in which he lodged. During his attendance he was always
perfectly decorous in his deportment, and when engaged in worship
had an air of great seriousness and devotion. The conductor and
frequenters of it had formerly been subjected to much obloquy, and
even violence, from the Catholics who abounded in that
neighbourhood; and one evening, after Burke’s attendance on it, his
landlord, Mikey Culzean, attempted to create annoyance, by
breaking through some sheets of paper which were used to cover up
an old window, and crying out in a voice of derision, “that the
performance was just going to begin.” Burke expressed himself in
indignant terms on the occasion, saying, that it was shameful and
unworthy of a man to behave in such a manner.
From the general aversion to the meeting so unequivocally
manifested by the Catholics, and Burke being universally known to
belong to that persuasion, his frequent attendance on it, and
reverential behaviour, excited the more notice. It was usual for him
to remain conversing with the individual in whose house they
assembled after the others had dispersed; and on these occasions
the subjects that had occupied their attention during the service
naturally were often talked over. His conversation was generally such
as to show that he had been attentive to what was passing, and
comprehended the topics brought under his notice. Since his
conviction he has adverted frequently to the subject, and deplored
that the meetings had been discontinued, as even this imperfect
form of public worship had a tendency to keep him from flagrant sin.
He has kept in his recollection, and mentioned after condemnation,
an expression which was used in one of the exhortations—“that
there was no standing still in sin.” His career of guilt, gradually
advancing in the commission of crime, until the violation of every
human and Divine law led him to most flagrant enormities, has
awakened him, by bitter experience, to give his unwilling testimony
to the justice of the remark.
During his residence in this neighbourhood, he gave no
indications of any thing that would lead people to anticipate his
future enormities. He was industrious and serviceable, inoffensive
and playful in his manner, and was never observed to drink to
excess. He was very fond of music and singing, in which he excelled,
and during his melancholy moods was most frequently found
chanting some favourite plaintive air. All these qualifications, and his
obliging manner, joined to a particularly jocular quizzical character,
with an interminable fund of low humour and drollery, rendered him
a general favourite. His custom was to take a walk almost daily
along the streets with an acquaintance, and freely to interfere in any
thing which occurred to indulge his humour. Some of these
occurrences are still recollected by his companions in his
perambulations, a specimen of which, as every thing concerning him
now seems to possess interest, may be given. In passing along the
Cowgate on one occasion, his musical ear was annoyed by the
continued inharmonious cry of an itinerant vender of salt. Upon her
approaching him still nearer, the annoyance reached its climax by
her drawling out in discordant sounds her reiteration of “wha’ll buy
saut;” though flinching under it, he turned and replied with his usual
politeness, “Upon my word I do not know, but if you will ask that
woman standing gaping at the door opposite, she will perhaps be
able to inform you.”
On another occasion, when attacked by a girl of the town in the
High Street, instead of replying directly to her solicitations, to the
astonishment of the unfortunate girl, he commenced a torrent of
abuse, on account of the awkward style in which she had painted
her face, saying that he might have passed over the painting, had it
been properly done; but that it was shameful to come to the street,
bedaubed in such an unskilful manner. Such was the humour with
which he continued his remonstrance, that the rude laugh of the
crowd was effectually directed against the amazed girl, and she was
glad, by a hasty retreat, to save herself from farther ridicule.
Though his conduct was such as has been described, and even to
his paramour, notwithstanding her irregular habits, partook most
frequently of his general character. Yet on several occasions, he
subjected her to ill usage, or sometimes rather, perhaps, returned
her violence, by relentlessly beating her. A fruitful source of quarrels,
was his propensity for the company of loose women, which, when
exhibited, never failed to rouse her jealousy. The most common
subject of it, was a near connection of her own, whose virtue was
not of an immaculate description. She was, however, a great
favourite of Burke’s and often was introduced into the house. In one
of these squabbles, a result was nearly produced, which might have
terminated both their lives, in a somewhat less notorious manner,
than his is likely to be, though more conducive to the public safety,
than his after impunity was, and exhibits the latent savageness of
his disposition, notwithstanding the fair exterior. One evening, Burke,
M‘Dougal, and the female already mentioned, had gone to bed
together. In the night, some jealousy had arisen between them, and
a battle was the consequence. So long as the conflict was
maintained on nearly equal terms, Burke contented himself with
witnessing it; but, when the elder virago was likely to master the
young one, he rose out of bed, and interfered in behalf of his
favourite. His interposition speedily turned the scale, and he inflicted
an unmerciful thrashing upon M‘Dougal. The neighbours who had
heard the uproar, but as usual, were backward in interfering, were
now alarmed by the cries of an interesting little girl, a daughter of
M‘Dougal’s by her former husband, who lived with them, and who
entreated them to assist her mother, as William Burke was
murdering her. Upon hastily rising and opening their doors, they
found M‘Dougal extended on the floor of the passage, apparently
lifeless, with her brutal companion standing by, contemplating her.
After some time, she exhibited signs of life, when, again seizing her
by the hair, and uttering a horrid imprecation, he exclaimed, “There
is life in her yet,” and dashed her head violently on the floor. The
police watchmen had by this time, been made aware of the noise,
and arrived immediately after this fresh inhumanity. Upon asking
Burke, if the woman was his wife, he again assumed his usual mild
manner, and in an insinuating tone said, “Yes, gentlemen, she is my
wife.”
After living for a year in Brown’s Close, he removed, still as
Culzean’s lodger, to Swan’s Close on the opposite side of the
Grassmarket, where he resided for some time still cobbling and
pursuing the same course of conduct. About this time, his
acquaintance with the individual who has furnished us with some of
the above particulars, suffered an interruption. Burke, although so
liberal in his intercourse with Protestants, had still enough of
Catholic feeling, as to take exceptions to his friend’s attending
Orange lodges, and a coolness in consequence ensued.
After leaving Swan’s Close, he went to Peebles, where he settled
for some years. He was employed there as a labourer, and went
daily to road-making in the neighbourhood of Innerleithen.
Here, although he still maintained some pretensions to religion,
we can trace a gradual deterioration in his character. From the note
formerly given, it will be seen that he was now distinguished for
keeping suspicious hours, and that his house was the resort of
profligate characters, and noted as the scene of drunkenness and
rioting, especially on Saturday nights and Sundays.
From thence he went to Pennicuik, where his conduct and
occupation were much the same, working generally as a labourer,
and occasionally following his self-taught occupation of mending
shoes.
After the harvest of 1827, he, still accompanied by M‘Dougal,
came again to reside in Edinburgh, and it was at this time that he
first became acquainted with the monster Hare, who was his
tempter to these unhallowed deeds, and his teacher, as well as
seducer. He came to live in Hare’s house in Tanner’s Close, West
Port, which was kept as a lodging-house by his wife, under the name
of her former husband Log. In this abode of profligacy and vice—the
resort of vagabonds of every description, and the theatre of
continued brawling and drunkenness, it is not surprising that every
trace of decent feeling that might still have lingered about him
should speedily be dispelled, and his mind be properly tutored and
prepared for the commencement of the murderous trade in which he
so ruthlessly continued for nearly twelve months.
An intimacy was speedily contracted between Hare and him, and
to show the vile footing on which the two families lived, we may
here relate an anecdote which was communicated by a respectable
neighbour of theirs, who called on Burke with the intention of giving
him a job as a cobbler. He found Hare most brutally beating the
woman M‘Dougal, who was lying on the floor, and Burke
unconcernedly sitting at the window. He asked Burke why he
suffered another man to beat his wife? to which he replied, “She
well deserved all she was getting.”
Burke still, however, maintained a more respectable character
than any of his partners; Hare was a rude and ferocious ruffian; his
wife was a meet companion for him; and M‘Dougal was very little
behind them in drunkenness and profanity. He continued, (unlike the
other three) to work a little at his business, in the inner small
apartment. The person who now shows Hare’s house is, along with
his other avocations, a dealer in old shoes, and used to employ him
to mend them up for sale. The stock of boots and shoes which was
found in Burke’s house upon their arrest, and which excited so much
speculation, belonged to him.
Previously to his becoming an inmate in Hare’s dwelling, he had
been in the habit of engaging in harvest work, first at Mr. Howden’s,
an extensive farmer in East Lothian, and subsequently with Mr.
Edington, farmer at Carlinden, near Carnwath, where Burke and
Hare, with their two women, wrought last harvest.
Of Burke, it had been observed, that he seemed to be a polite,
obliging, and industrious person. In rainy weather, while the reapers
could not work in the fields, it was usual for him to find out some
useful service, which he performed at the farm-steading; so that he
was seldom, if ever, idle. Whenever it happened that a servant had
any heavy article to lift, he, of all the harvest people assembled in
the kitchen, was the foremost to offer his assistance. On a young
woman’s mentioning that she had never seen Edinburgh, the same
courteous Burke invited her to town, saying, that he would give her
a lodging in his own house, and that he would show her the city;
but, fortunately, she never had an opportunity of availing herself of
his kindness. After a stay of a few days at Carlinden, a letter arrived,
which was said to announce the illness of a child of Hare’s, in
Edinburgh; the parents began to arrange for their returning
homeward, when M‘Dougal remarked, that “if Hare goes, William
Burke will go too, for they are like brothers, and cannot be
separated.” Accordingly, all the four went off together.
While he resided in the West Port, he was remarked to be a very
early riser, frequently appearing on the streets in his working dress,
on a summer morning by three or four o’clock; some who were also
on foot at these early hours, used to observe him, and taunt the
shoemakers of the West Port with the observation that the Irish lad
was the most industrious man among them. It is probable that this
activity was for a very different purpose to what was suspected.
The first dealing in subjects commenced in a manner which few
would be inclined to visit with very great reprehension, and had the
pair throughout confined themselves to similar exploits, they would
probably have been regarded as adroit and ingenious knaves,
perhaps more beneficially employed in furnishing the necessary
supply of subjects in a manner which harmed no one, than from
their bad habits they were likely otherwise to be.
In December 1827, the natural death of a lodger happened in
Hare’s house,—not of a woman, as has been erroneously stated, but
of a very tall and stout man, a pensioner who led a dissipated good-
for-nothing life. His debauched habits sufficiently account for his
death, while yet in the vigour of life, without any suspicion of unfair
agency being aroused.
After his decease, the ordinary observances were gone through,
and all matters fitly prepared for the funeral; a coffin was procured,
and the funeral guests invited, and every thing managed in a
decorous manner; the undertaker came, and while employed in
fastening down the lid, was invited into the other room to recruit his
strength by a dram, the coffin was then uncovered, and the corpse
quickly dislodged and made to change situations with a sack of
waste bark which had been previously procured from a neighbouring
tannery. After this, the fastening proceeded. The coffin was borne
out at the appointed time, before the assembled guests, and with all
due solemnity deposited in the Grey Friars churchyard. The rogues,
after the ceremony, proceeded to find out a purchaser for the body,
and so unacquainted were they with the manner of proceeding, that
they did not at first apply to the proper quarter. Throughout the day,
however, they found this out, and at dusk the subject was conveyed
away in the sack which had held the bark, and was carried on
Burke’s back. Their first resting place was at Bristo Port, where it
was set down for a little, when Hare took his share of the burden.
They then took the round-about road of College Street to Surgeons’
Square. They soon afterwards, however, found out the nearest way.
After all that has been said, subjects must be procured for
scientific purposes; the necessity of a young man under a course of
education for surgical practice qualifying himself for his future
profession by anatomical dissections, renders them indispensable,
while the very ordinances and regulations of the College of
Surgeons, makes dissection imperative before he can obtain a
diploma or license to follow his profession. Were all subjects
procured in this harmless way, where neither the feelings of private
friends were outraged, nor public decency violated, small fault would
be found, though the nature of the traffic would continue still
sufficiently revolting to deter all but ruthless blackguards from
embarking in it.
But after once gaining what to them was a large sum of money,
Burke’s and Hare’s cupidity could not be satisfied with this
comparatively innocent method of supplying their wants. They were
apparently too indolent or inexpert, or lacked courage too much, to
adopt the ordinary but hazardous mode of raising the dead from
church-yards. Still, with this easy, and apparently unlimited means of
acquiring money opening to them, they could not betake themselves
again to the pursuits of honest industry; and, stimulated by the
greatness of the reward, and the prospect of their sensual
indulgences being so readily gratified, they formed the desperate
resolution of committing murder, and of continuing to imbrue their
hands in their fellow-mortals’ blood, as their ordinary and sole
means of procuring a livelihood.
Before commencing the revolting narrative of their appalling
crimes, we may mention, that previous to the period in which they
engaged in them, their neighbours used to observe them only to
notice the squalor and wretchedness of their appearance; but all at
once, there was a sudden change, and Burke and M‘Dougal
especially assumed a different aspect. They appeared well dressed,
and spent money freely. Whisky, which however much it may be
relished, can only be procured at intervals by men in his situation,
seemed to be constantly at their command; and even credit at a
neighbouring spirit-dealer and grocer’s, was obtained, to an extent
that almost no individual in his situation would have ventured to
hope for or request. At this time, Burke mentioned to the wife of an
old acquaintance, whom he met accidentally, that he had spent
fourteen pounds within the last fortnight; and if he had known
where her husband lived, would have been glad to come and spend
three or four pounds in company with him. Of course, all this
apparent affluence was not exhibited, without exciting the
speculation of those who observed it; and they were troublesome in
their inquiries into the secret, that enabled them to live well, and
drink continually, without working. Various were the excuses that
were made; for they never appear to have been at a loss for an
answer. On one occasion, when the question was put to Burke, and
suspicions intimated, that he followed the trade of a resurrection
man, he neither would give a denial nor an affirmative to the
proposition, but contented himself with remarking, that the querist
was as bad as the rest. On another, he would ask Mrs. —— “Can you
keep a secret,” and when the curious inquirer, expecting to be
entrusted with the whole mystery, eagerly answered, “Yes,” he
would reply, with an air of secrecy, that he smuggled a little small-
still whisky.
Nelly M‘Dougal had a different way of accounting for it. She
averred that she had a property in Stirlingshire, which had been left
to her by her former husband, and which produced twenty pounds a
year; and that it was from the rent of it the money came. It was
afterwards observed to her by some of the neighbours, that this
story would scarcely account for their abundant supply of money, as
the rents of such properties, as she described, were usually drawn at
definite terms, and they seemed to get money much more
frequently. She then alleged that the money was the proceeds of a
legacy that had been lately left her, and that she drew part of it
when she pleased. To humour this story, she used to announce to
her acquaintances, from time to time, that their money was
expended, and that she had written off for a fresh supply. In a few
days, accordingly, she intimated that the money had arrived, and
new vigour was imparted to their drunken disorderly courses.
It must be perfectly apparent what the dispatching of the letter
meant, and if these proceedings does not amount to a guilty
knowledge and accession to the murders, so far as knowledge of,
and sharing in the proceeds goes, we do not comprehend what can
constitute participation.
At another time she intimated that William [Burke] was the
favourite of a lady in the New Town, who never allowed him to want
money, and sometimes she had known him receive twenty pounds at
a time from her.
Burke states, that Hare and he had often talked over the subject
of murder, and had consulted upon the best mode of effecting it. It
may well be credited, as their first essay seems to have been
conducted with as much coolness and deliberation, as much cautious
management in effecting it, and as little compunction in the
execution, as if they already had been adepts in the art. It was
perpetrated on an elderly woman, belonging to the village of
Gilmerton, whom Hare had observed a little intoxicated on the
streets. She was a pensioner to a gentleman in the New Town, from
whom she received 1s. 6d. a week. Hare accosted her, and easily
succeeded in enticing her into his house, here they gave her spirits
to drink, and afterwards Mrs. Hare, purchased, for one shilling and
sixpence, a small cann of kitchen-fee which she had received at the
house of the gentleman already mentioned. The price of it was also
laid out in liquor, and the poor woman speedily got altogether
intoxicated, and commenced singing in the exuberance of her mirth.
She told them that she had a very fine young daughter at home,
and, with maternal feeling, was loud in her praises. Hare
represented himself as an unmarried man, and said, that upon her
representation, he would marry her daughter: The poor woman
readily consented to the match, when the heartless fiend, expressed
great kindness for her, and alleged that his bride and he could not
live without her, and that when the daughter came home, she must
come to reside with them. She willingly consented to this
arrangement, and expressed herself quite overjoyed at meeting with
such a good provision for herself and daughter, and promised to
return and get the marriage consummated. They took care to ply
her well with liquor, in order that being made completely drunk, she
might remain after the other lodgers had departed in the morning.
Next day, the spirits had the effect, and she was sick and vomited.
The monsters had not abandoned their purpose, however, and after
stupifying her with more whisky, when all the others had left the
house, they put her to death in the way they pursued ever
afterwards, by covering and pressing upon the nose and mouth with
their hands. The body was afterwards conveyed to Surgeons’
Square, and the money readily obtained for it. This happened in
December 1827.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like