Learning Concurrent Programming in Scala Second Edition Aleksandar Prokopec
Learning Concurrent Programming in Scala Second Edition Aleksandar Prokopec Learning Concurrent Programming in Scala Second Edition Aleksandar Prokopec Learning Concurrent Programming in Scala Second Edition Aleksandar Prokopec
Learning Concurrent Programming in Scala Second Edition Aleksandar Prokopec
1.
Read Anytime AnywhereEasy Ebook Downloads at ebookmeta.com Learning Concurrent Programming in Scala Second Edition Aleksandar Prokopec https://ebookmeta.com/product/learning-concurrent- programming-in-scala-second-edition-aleksandar-prokopec/ OR CLICK HERE DOWLOAD EBOOK Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com
2.
Recommended digital products(PDF, EPUB, MOBI) that you can download immediately if you are interested. Learning Concurrent Programming in Scala Second Edition Aleksandar Prokopec https://ebookmeta.com/product/learning-concurrent-programming-in- scala-second-edition-aleksandar-prokopec/ ebookmeta.com Functional Programming in Scala, Second Edition (MEAP V08) Michael Pilquist https://ebookmeta.com/product/functional-programming-in-scala-second- edition-meap-v08-michael-pilquist/ ebookmeta.com Programming in Scala Fifth Edition Martin Odersky https://ebookmeta.com/product/programming-in-scala-fifth-edition- martin-odersky/ ebookmeta.com The Wills Eye Manual Office and Emergency Room Diagnosis and Treatment of Eye Disease Kalla Gervasio https://ebookmeta.com/product/the-wills-eye-manual-office-and- emergency-room-diagnosis-and-treatment-of-eye-disease-kalla-gervasio/ ebookmeta.com
3.
The Politics ofNonpartisanship A Study of California City Elections Eugene C. Lee https://ebookmeta.com/product/the-politics-of-nonpartisanship-a-study- of-california-city-elections-eugene-c-lee/ ebookmeta.com CCSP Certified Cloud Security Professional. Exam Guide 3rd Edition Unknown https://ebookmeta.com/product/ccsp-certified-cloud-security- professional-exam-guide-3rd-edition-unknown/ ebookmeta.com Nonlinear Modeling Analysis and Predistortion Algorithm Research of Radio Frequency Power Amplifiers 1st Edition Jingchang Nan https://ebookmeta.com/product/nonlinear-modeling-analysis-and- predistortion-algorithm-research-of-radio-frequency-power- amplifiers-1st-edition-jingchang-nan-2/ ebookmeta.com My Life in the Ring and Out Jack Johnson https://ebookmeta.com/product/my-life-in-the-ring-and-out-jack- johnson/ ebookmeta.com Engineering Optimization Solution manual 4th Edition Singiresu S Rao Ss Rao Suganth V https://ebookmeta.com/product/engineering-optimization-solution- manual-4th-edition-singiresu-s-rao-ss-rao-suganth-v/ ebookmeta.com
4.
The Handbook ofArt and Design Librarianship 2nd Edition Paul Glassman https://ebookmeta.com/product/the-handbook-of-art-and-design- librarianship-2nd-edition-paul-glassman/ ebookmeta.com
6.
Table of Contents LearningConcurrent Programming in Scala - Second Edition Credits Foreword About the Author Acknowledgements About the Reviewers www.PacktPub.com Why subscribe? Customer Feedback Preface What this book covers What you need for this book Installing the JDK Installing and using SBT Using Eclipse, IntelliJ IDEA, or another IDE Who this book is for Conventions Reader feedback Customer support Downloading the example code Downloading the color images of this book Errata Piracy Questions 1. Introduction Concurrent programming A brief overview of traditional concurrency Modern concurrency paradigms The advantages of Scala Preliminaries Execution of a Scala program A Scala primer
7.
Overview of newfeatures in Scala 2.12 Summary Exercises 2. Concurrency on the JVM and the Java Memory Model Processes and threads Creating and starting threads Atomic execution Reordering Monitors and synchronization Deadlocks Guarded blocks Interrupting threads and the graceful shutdown Volatile variables The Java Memory Model Immutable objects and final fields Summary Exercises 3. Traditional Building Blocks of Concurrency The Executor and ExecutionContext objects Atomic primitives Atomic variables Lock-free programming Implementing locks explicitly The ABA problem Lazy values Concurrent collections Concurrent queues Concurrent sets and maps Concurrent traversals Custom concurrent data structures Implementing a lock-free concurrent pool Creating and handling processes Summary Exercises 4. Asynchronous Programming with Futures and Promises Futures
8.
Starting future computations Futurecallbacks Futures and exceptions Using the Try type Fatal exceptions Functional composition on futures Promises Converting callback-based APIs Extending the future API Cancellation of asynchronous computations Futures and blocking Awaiting futures Blocking in asynchronous computations The Scala Async library Alternative future frameworks Summary Exercises 5. Data-Parallel Collections Scala collections in a nutshell Using parallel collections Parallel collection class hierarchy Configuring the parallelism level Measuring the performance on the JVM Caveats with parallel collections Non-parallelizable collections Non-parallelizable operations Side effects in parallel operations Nondeterministic parallel operations Commutative and associative operators Using parallel and concurrent collections together Weakly consistent iterators Implementing custom parallel collections Splitters Combiners Summary Exercises
9.
6. Concurrent Programmingwith Reactive Extensions Creating Observable objects Observables and exceptions The Observable contract Implementing custom Observable objects Creating Observables from futures Subscriptions Composing Observable objects Nested Observables Failure handling in Observables Rx schedulers Using custom schedulers for UI applications Subjects and top-down reactive programming Summary Exercises 7. Software Transactional Memory The trouble with atomic variables Using Software Transactional Memory Transactional references Using the atomic statement Composing transactions The interaction between transactions and side effects Single-operation transactions Nesting transactions Transactions and exceptions Retrying transactions Retrying with timeouts Transactional collections Transaction-local variables Transactional arrays Transactional maps Summary Exercises 8. Actors Working with actors Creating actor systems and actors
10.
Managing unhandled messages Actorbehavior and state Akka actor hierarchy Identifying actors The actor lifecycle Communication between actors The ask pattern The forward pattern Stopping actors Actor supervision Remote actors Summary Exercises 9. Concurrency in Practice Choosing the right tools for the job Putting it all together - a remote file browser Modeling the filesystem The server interface Client navigation API The client user interface Implementing the client logic Improving the remote file browser Debugging concurrent programs Deadlocks and lack of progress Debugging incorrect program outputs Performance debugging Summary Exercises 10. Reactors The need for reactors Getting started with Reactors The "Hello World" program Event streams Lifecycle of an event stream Functional composition of event streams Reactors
11.
Defining and configuringreactors Using channels Schedulers Reactor lifecycle Reactor system services The logging service The clock service The channels service Custom services Protocols Custom server-client protocol Standard server-client protocol Using an existing connector Creating a new connector Creating a protocol-specific reactor prototype Spawning a protocol-specific reactor directly Router protocol Two-way protocol Summary Exercises
Foreword Concurrent and parallelprogramming have progressed from niche disciplines, of interest only to kernel programming and high- performance computing, to something that every competent programmer must know. As parallel and distributed computing systems are now the norm, most applications are concurrent, be it for increasing the performance or for handling asynchronous events. So far, most developers are unprepared to deal with this revolution. Maybe they have learned the traditional concurrency model, which is based on threads and locks, in school, but this model has become inadequate for dealing with massive concurrency in a reliable manner and with acceptable productivity. Indeed, threads and locks are hard to use and harder to get right. To make progress, one needs to use concurrency abstractions that are at a higher level and composable. 15 years ago, I worked on a predecessor of Scala: Funnel was an experimental programming language that had concurrent semantics at its core. All the programming concepts were explained in this language as syntactic sugar on top of functional nets, an object- oriented variant of join calculus . Even though join calculus is a beautiful theory, we realized after some experimentation that the concurrency problem is more multifaceted than what can be comfortably expressed in a single formalism. There is no silver bullet for all concurrency issues; the right solution depends on what one needs to achieve. Do you want to define asynchronous computations that react to events or streams of values? Or have autonomous, isolated entities communicating via messages? Or define transactions over a mutable store? Or, maybe the primary purpose of parallel execution is to increase the performance? For each of these tasks, there is an abstraction that does the job: futures, reactive streams, actors, transactional memory, or parallel collections.
19.
This brings usto Scala and this book. As there are so many useful concurrency abstractions, it seems unattractive to hardcode them all in a programming language. The purpose behind the work on Scala was to make it easy to define high-level abstractions in user code and libraries. This way, one can define the modules handling the different aspects of concurrent programming. All of these modules would be built on a low-level core that is provided by the host system. In retrospect, this approach has worked well. Today, Scala has some of the most powerful and elegant libraries for concurrent programming. This book will take you on a tour of the most important ones, explaining the use case for each and the application patterns. This book could not have a more expert author. Aleksandar Prokopec contributed to some of the most popular Scala libraries for concurrent and parallel programming. He also invented some of the most intricate data structures and algorithms. With this book, he created a readable tutorial at the same time and an authoritative reference for the area that he had worked in. I believe that Learning Concurrent Programming in Scala, Second Edition will be a mandatory reading for everyone who writes concurrent and parallel programs in Scala. I also expect to see it on the bookshelves of many people who just want to find out about this fascinating and fast moving area of computing. Martin Odersky Professor at EPFL, the creator of Scala
20.
About the Author AleksandarProkopec, who also authored the first edition of this book, is a concurrent and distributed programming researcher. He holds a PhD in computer science from the École Polytechnique Fédérale de Lausanne, Switzerland. He has worked at Google and is currently a principal researcher at Oracle Labs. As a member of the Scala team at EPFL, Aleksandar actively contributed to the Scala programming language, and he has worked on programming abstractions for concurrency, data-parallel programming support, and concurrent data structures for Scala. He created the Scala Parallel Collections framework, which is a library for high-level data-parallel programming in Scala, and participated in working groups for Scala concurrency libraries, such as Futures, Promises, and ScalaSTM. Aleksandar is the primary author of the reactor programming model for distributed computing.
21.
Acknowledgements First of all,I would like to thank my reviewers, Samira Tasharofi, Lukas Rytz, Dominik Gruntz, Michel Schinz, Zhen Li, and Vladimir Kostyukov for their excellent feedback and useful comments. I would also like to thank the editors at Packt, Kevin Colaco, Sruthi Kutty, Kapil Hemnani, Vaibhav Pawar, and Sebastian Rodrigues for their help with writing this book. It really was a pleasure to work with these people. The concurrency frameworks described in this book wouldn’t have seen the light of the day without a collaborative effort of a large number of people. Many individuals have somehow, directly or indirectly, contributed to the development of these utilities. These people are the true heroes of Scala concurrency, and they are to thank for Scala’s excellent support for concurrent programming. It is difficult to enumerate all of them here, but I tried my best. If somebody feels left out, they should ping me, and, they’ll probably appear in the next edition of this book. It goes without saying that Martin Odersky is to thank for creating the Scala programming language, which was used as a platform for the concurrency frameworks described in this book. Special thanks goes to him, all the people that were part of the Scala team at the EPFL through the last 10 or more years, and the people at Typesafe, who are working hard to keep Scala one of the best general purpose languages out there. Most of the Scala concurrency frameworks rely on the work of Doug Lea, in one way or another. His Fork/Join framework underlies the implementation of the Akka actors, Scala Parallel Collections, and the Futures and Promises library, and many of the JDK concurrent data structures described in this book are his own implementation. Many of the Scala concurrency libraries were influenced by his advice.
22.
The Scala Futuresand Promises library was initially designed by Philipp Haller, Heather Miller, Vojin Jovanović, and me from the EPFL, Viktor Klang and Roland Kuhn from the Akka team, and Marius Eriksen from Twitter, with contributions from Havoc Pennington, Rich Dougherty, Jason Zaugg, Doug Lea, and many others. Although I was the main author of the Scala Parallel Collections, this library benefited from the input of many different people, including Phil Bagwell, Martin Odersky, Tiark Rompf, Doug Lea, and Nathan Bronson. Later on, Dmitry Petrashko and I started working on an improved version of parallel and standard collection operations, optimized through the use of Scala Macros. Eugene Burmako and Denys Shabalin are one of the main contributors to the Scala Macros project. The work on the Rx project was started by Erik Meijer, Wes Dyer, and the rest of the Rx team. Since its original .NET implementation, the Rx framework has been ported to many different languages, including Java, Scala, Groovy, JavaScript, and PHP, and has gained widespread adoption thanks to the contributions and the maintenance work of Ben Christensen, Samuel Grütter, Shixiong Zhu, Donna Malayeri, and many other people. Nathan Bronson is one of the main contributors to the ScalaSTM project, whose default implementation is based on Nathan’s CCSTM project. The ScalaSTM API was designed by the ScalaSTM expert group, composed of Nathan Bronson, Jonas Bonér, Guy Korland, Krishna Sankar, Daniel Spiewak, and Peter Veentjer. The initial Scala actor library was inspired by the Erlang actor model and developed by Philipp Haller. This library inspired Jonas Bonér to start the Akka actor framework. The Akka project had many contributors, including Viktor Klang, Henrik Engström, Peter Vlugter, Roland Kuhn, Patrik Nordwall, Björn Antonsson, Rich Dougherty, Johannes Rudolph, Mathias Doenitz, Philipp Haller, and many others.
23.
Finally, I wouldlike to thank the entire Scala community for their contributions, and for making Scala an awesome programming language.
24.
About the Reviewers VikashSharma is a software developer and open source technology evangelist, located in India. He tries to keep things simple and that helps him writing clean and manageable code. He has authored a video course for Scala. He is employed as an associate consultant with Infosys and has also worked as a Scala developer. Thank you would not suffice for the support I got from my family, Mom, Dad and Brother. I really want to appreciate everyone who were there when I needed them the most. Special thanks to Vijay Athikesavan for passing to me the insights he had for coding. Dominik Gruntz has a PhD from ETH Zürich and has been a Professor of Computer Science at the University of Applied Sciences FHNW since 2000. Besides his research projects, he teaches a course on concurrent programming. Some years ago, the goal of this course was to convince the students that writing correct concurrent programs is too complicated for mere mortals (an educational objective that was regularly achieved). With the availability of high- level concurrency frameworks in Java and Scala, this has changed, and this book, Learning Concurrent Programming in Scala, is a great resource for all programmers who want to learn how to write correct, readable, and efficient concurrent programs. This book is the ideal textbook for a course on concurrent programming. Thanks that I could support this project as a reviewer. Zhen Li acquired an enthusiasm of computing early in elementary school when she first learned Logo. After earning a Software Engineering degree at Fudan University in Shanghai, China and a
25.
Computer Science degreefrom University College Dublin, Ireland, she moved to the University of Georgia in the United States for her doctoral tudy and research. She focused on psychological aspects of programmers' learning behaviors, especially the way programmers understand concurrent programs. Based on the research, she aimed to develop effective software engineering methods and teaching paradigms to help programmers embrace concurrent programs. Zhen Li had practical teaching experience with undergraduate students on a variety of computer science topics, including system and network programming, modeling and simulation, as well as human-computer interaction. Her major contributions in teaching computer programming were to author syllabi and offer courses with various programming languages and multiple modalities of concurrency that encouraged students to actively acquire software design philosophy and comprehensively learn programming concurrency. Zhen Li also had a lot of working experience in industrial innovations. She worked in various IT companies, including Oracle, Microsoft, and Google, over the past 10 years, where she participated in the development of cutting-edge products, platforms and infrastructures for core enterprise, and Cloud business technologies. Zhen Li is passionate about programming and teaching. You are welcome to contact her at janeli@uga.edu. Lukas Rytz is a compiler engineer working in the Scala team at Typesafe. He received his PhD from EPFL in 2013, and has been advised by Martin Odersky, the inventor of the Scala programming language. Michel Schinz is a lecturer at EPFL. Samira Tasharofi received her PhD in the field of Software Engineering from the University of Illinois at Urbana-Champaign. She has conducted research on various areas, such as testing concurrent
26.
programs and inparticular actor programs, patterns in parallel programming, and verification of component-based systems. Samira has reviewed several books, such as Actors in Scala, Parallel Programming with Microsoft .NET: Design Patterns for Decomposition and Coordination on Multicore Architectures (Patterns and Practices), and Parallel Programming with Microsoft Visual C++: Design Patterns for Decomposition and Coordination on Multicore Architectures (Patterns and Practices). She was also among the reviewers of the research papers for software engineering conferences, including ASE, AGERE, SPLASH, FSE, and FSEN. She has served as a PC member of the 4th International Workshop on Programming based on Actors, Agents, and Decentralized Control (AGERE 2014) and 6th IPM International Conference on Fundamentals of Software Engineering (FSEN 2015). I would like to thank my husband and mom for their endless love and support.
27.
www.PacktPub.com For support filesand downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. https://www.packtpub.com/mapt Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry- leading tools to help you plan your personal development and advance your career.
28.
Why subscribe? Fully searchableacross every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser
29.
Customer Feedback Thanks forpurchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://goo.gl/ldH2Nv. If you'd like to join our team of regular reviewers, you can email us at customerreviews@packtpub.com. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products! Dedicated to Sasha, She’s probably the only PhD in physical chemistry ever to read this book.
30.
Preface Concurrency is everywhere.With the rise of multicore processors in the consumer market, the need for concurrent programming has overwhelmed the developer world. Where it once served to express asynchronously in programs and computer systems and was largely an academic discipline, concurrent programming is now a pervasive methodology in software development. As a result, advanced concurrency frameworks and libraries are sprouting at an amazing rate. Recent years have witnessed a renaissance in the field of concurrent computing. As the level of abstraction grows in modern languages and concurrency frameworks, it is becoming crucial to know how and when to use them. Having a good grasp of the classical concurrency and synchronization primitives, such as threads, locks, and monitors, is no longer sufficient. High-level concurrency frameworks, which solve many issues of traditional concurrency and are tailored towards specific tasks, are gradually overtaking the world of concurrent programming. This book describes high-level concurrent programming in Scala. It presents detailed explanations of various concurrency topics and covers the basic theory of concurrent programming. Simultaneously, it describes modern concurrency frameworks, shows their detailed semantics, and teaches you how to use them. Its goal is to introduce important concurrency abstractions and, at the same time, show how they work in real code. We are convinced that, by reading this book, you will gain both a solid theoretical understanding of concurrent programming and develop a set of useful practical skills that are required to write correct and efficient concurrent programs. These skills are the first steps toward becoming a modern concurrency expert.
31.
We hope thatyou will have as much fun reading this book as we did writing it.
32.
What this bookcovers This book is organized into a sequence of chapters with various topics on concurrent programming. The book covers the fundamental concurrent APIs that are a part of the Scala runtime, introduces more complex concurrency primitives, and gives an extensive overview of high-level concurrency abstractions. Chapter 1, Introduction, explains the need for concurrent programming and gives some philosophical background. At the same time, it covers the basics of the Scala programming language that are required for understanding the rest of this book. Chapter 2, Concurrency on the JVM and the Java Memory Model, teaches you the basics of concurrent programming. This chapter will teach you how to use threads and how to protect access to shared memory and introduce the Java Memory Model. Chapter 3, Traditional Building Blocks of Concurrency, presents classic concurrency utilities, such as thread pools, atomic variables, and concurrent collections, with a particular focus on the interaction with the features of the Scala language. The emphasis in this book is on the modern, high-level concurrent programming frameworks. Consequently, this chapter presents an overview of traditional concurrent programming techniques, but it does not aim to be extensive. Chapter 4, Asynchronous Programming with Futures and Promises, is the first chapter that deals with a Scala-specific concurrency framework. This chapter presents the futures and promises API and shows how to correctly use them when implementing asynchronous programs. Chapter 5, Data-Parallel Collections, describes the Scala parallel collections framework. In this chapter, you will learn how to
33.
parallelize collection operations,when it is allowed to parallelize them, and how to assess the performance benefits of doing so. Chapter 6, Concurrent Programming with Reactive Extensions, teaches you how to use the Reactive Extensions framework for event-based and asynchronous programming. You will see how the operations on event streams correspond to collection operations, how to pass events from one thread to another, and how to design a reactive user interface using event streams. Chapter 7, Software Transactional Memory, introduces the ScalaSTM library for transactional programming, which aims to provide a safer, more intuitive, shared-memory programming model. In this chapter, you will learn how to protect access to shared data using scalable memory transactions and, at the same time, reduce the risk of deadlocks and race conditions. Chapter 8, Actors, presents the actor programming model and the Akka framework. In this chapter, you will learn how to transparently build message-passing distributed programs that run on multiple machines. Chapter 9, Concurrency in Practice, summarizes the different concurrency libraries introduced in the earlier chapters. In this chapter, you will learn how to choose the correct concurrency abstraction to solve a given problem, and how to combine different concurrency abstractions together when designing larger concurrent applications. Chapter 10, Reactors, presents the reactor programming model, whose focus is improved composition in concurrent and distributed programs. This emerging model enables separation of concurrent and distributed programming patterns into modular components called protocols. While we recommend that you read the chapters in the order in which they appear, this is not strictly necessary. If you are well
34.
acquainted with thecontent in Chapter 2, Concurrency on the JVM and the Java Memory Model, you can study most of the other chapters directly. The only chapters that rely on the content from all the preceding chapters are Chapter 9, Concurrency in Practice, where we present a practical overview of the topics in this book, and Chapter 10, Reactors, for which it is helpful to understand how actors and event streams work.
35.
What you needfor this book In this section, we describe some of the requirements that are necessary to read and understand this book. We explain how to install the Java Development Kit, which is required to run Scala programs and show how to use Simple Build Tool to run various examples. We will not require an IDE in this book. The program that you use to write code is entirely up to you, and you can choose anything, such as Vim, Emacs, Sublime Text, Eclipse, IntelliJ IDEA, Notepad++, or some other text editor.
36.
Installing the JDK Scalaprograms are not compiled directly to the native machine code, so they cannot be run as executables on various hardware platforms. Instead, the Scala compiler produces an intermediate code format called the Java bytecode. To run this intermediate code, your computer must have the Java Virtual Machine software installed. In this section, we explain how to download and install the Java Development Kit, which includes the Java Virtual Machine and other useful tools. There are multiple implementations of the JDK that are available from different software vendors. We recommend that you use the Oracle JDK distribution. To download and install the Java Development Kit, follow these steps: 1. Open the following URL in your web browser: www.oracle.com/technetwork/java/javase/downloads/index.html . 2. If you cannot open the specified URL, go to your search engine and enter the keywords JDK Download. 3. Once you find the link for the Java SE, download on the Oracle website, download the appropriate version of JDK 7 for your operating system: Windows, Linux, or Mac OS X; 32-bit or 64- bit. 4. If you are using the Windows operating system, simply run the installer program. If you are using the Mac OS X, open the dmg archive to install JDK. Finally, if you are using Linux, decompress the archive to a XYZ directory, and add the bin subdirectory to the PATH variable: export PATH=XYZ/bin:$PATH 5. You should now be able to run the java and javac commands in the terminal. Enter the javac command to see if it is available
37.
(you will neverinvoke this command directly in this book, but running it verifies that it is available). It is possible that your operating system already has JDK installed. To verify this, simply run the javac command, as we did in the last step in the preceding description.
38.
Installing and usingSBT Simple Build Tool (SBT) is a command-line build tool used for Scala projects. Its purpose is to compile Scala code, manage dependencies, continuous compilation and testing, deployment, and many other uses. Throughout this book, we will use SBT to manage our project dependencies and run example code. To install SBT, follow these instructions: 1. Go to the http://www.scala-sbt.org/ URL. 2. Download the installation file for your platform. If you are running on Windows, this is the msi installer file. If you are running on Linux or OS X, this is the zip or tgz archive file. 3. Install SBT. If you are running on Windows, simply run the installer file. If you are running on Linux or OS X, unzip the contents of the archive in your home directory. You are now ready to use SBT. In the following steps, we will create a new SBT project: 1. Open a Command Prompt if you are running on Windows, or a terminal window if you are running on Linux or OS X. 2. Create an empty directory called scala-concurrency-examples: $ mkdir scala-concurrency-examples 3. Change your path to the scala-concurrency-examples directory: $ cd scala-concurrency-examples 4. Create a single source code directory for our examples: $ mkdir src/main/scala/org/learningconcurrency/
39.
5. Now, useyour editor to create a build definition file named build.sbt. This file defines various project properties. Create it in the root directory of the project (scala-concurrency-examples). Add the following contents to the build definition file (note that the empty lines are mandatory): name := "concurrency-examples" version := "1.0" scalaVersion := "2.11.1" 6. Finally, go back to the terminal and run SBT from the root directory of the project: $ sbt 7. SBT will start an interactive shell, which we will use to give SBT various build commands. Now, you can start writing Scala programs. Open your editor, and create a source code file named HelloWorld.scala in the src/main/scala/org/learningconcurrency directory. Add the following contents to the HelloWorld.scala file: package org.learningconcurrency object HelloWorld extends App { println("Hello, world!") } Now, go back to the terminal window with the SBT interactive shell and run the program with the following command: > run Running this program should give the following output:
40.
Hello, world! These stepsare sufficient to run most of the examples in this book. Occasionally, we will rely on external libraries when running the examples. These libraries are resolved automatically by SBT from standard software repositories. For some libraries, we will need to specify additional software repositories, so we add the following lines to our build.sbt file: resolvers ++= Seq( "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/sna pshots", "Sonatype OSS Releases" at "https://oss.sonatype.org/content/repositories/rel eases", "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/" ) Now that we have added all the necessary software repositories, we can add some concrete libraries. By adding the following line to the build.sbt file, we obtain access to the Apache Commons IO library: libraryDependencies += "commons-io" % "commons-io" % "2.4" After changing the build.sbt file, it is necessary to reload any running SBT instances. In the SBT interactive shell, we need to enter the following command: > reload
41.
This enables SBTto detect any changes in the build definition file and download additional software packages when necessary. Different Scala libraries live in different namespaces called packages. To obtain access to the contents of a specific package, we use the import statement. When we use a specific concurrency library in an example for the first time, we will always show the necessary set of import statements. On subsequent uses of the same library, we will not repeat the same import statements. Similarly, we avoid adding package declarations in the code examples to keep them short. Instead, we assume that the code in a specific chapter is in the similarly named package. For example, all the code belonging to Chapter 2, Concurrency on the JVM and the Java Memory Model, resides in the org.learningconcurrency.ch2 package. Source code files for the examples presented in that chapter begin with the following code: package org.learningconcurrency package ch2 Finally, this book deals with concurrency and asynchronous execution. Many of the examples start a concurrent computation that continues executing after the main execution stops. To make sure that these concurrent computations always complete, we will run most of the examples in the same JVM instance as SBT itself. We add the following line to our build.sbt file: fork := false In the examples, where running in a separate JVM process is required, we will point this out and give clear instructions.
42.
Using Eclipse, IntelliJIDEA, or another IDE An advantage of using an Integrated Development Environment (IDE) such as Eclipse or IntelliJ IDEA is that you can write, compile, and run your Scala programs automatically. In this case, there is no need to install SBT, as described in the previous section. While we advise that you run the examples using SBT, you can alternatively use an IDE. There is an important caveat when running the examples in this book using an IDE: editors such as Eclipse and IntelliJ IDEA run the program inside a separate JVM process. As mentioned in the previous section, certain concurrent computations continue executing after the main execution stops. To make sure that they always complete, you will sometimes need to add the sleep statements at the end of the main execution, which slow down the main execution. In most of the examples in this book, the sleep statements are already added for you, but in some programs, you might have to add them yourself.
43.
Who this bookis for This book is primarily intended for developers who have learned how to write sequential Scala programs, and wish to learn how to write correct concurrent programs. The book assumes that you have a basic knowledge of the Scala programming language. Throughout this book, we strive to use the simple features of Scala in order to demonstrate how to write concurrent programs. Even with an elementary knowledge of Scala, you should have no problem understanding various concurrency topics. This is not to say that the book is limited to Scala developers. Whether you have experience with Java, come from a .NET background, or are generally a programming language aficionado, chances are that you will find the content in this book insightful. A basic understanding of object-oriented or functional programming should be a sufficient prerequisite. Finally, this book is a good introduction to modern concurrent programming in the broader sense. Even if you have the basic knowledge about multithreaded computing, or the JVM concurrency model, you will learn a lot about modern, high-level concurrency utilities. Many of the concurrency libraries in this book are only starting to find their way into mainstream programming languages, and some of them are truly cutting-edge technologies.
44.
Conventions In this book,you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The next lines of code read the link and assign it to the to the BeautifulSoup function." A block of code is set as follows: package org package object learningconcurrency { def log(msg: String): Unit = println(s"${Thread.currentThread.getName}: $msg") } When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: object ThreadsMain extends App { val t: Thread = Thread.currentThread val name = t.getName println(s"I am the thread $name") } Any command-line input or output is written as follows: $ mkdir scala-concurrency-examples New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "In order to download new modules, we
heathens, and constantlyto say of us, "Non sanno meglio, non sono Cristiani." It was something more than all this which ever filled me with a feeling of intense devotion when I entered that grand old building. The severe simplicity of the structure, with no tawdry ornamentation to obtrude itself and take off the attention, may have played an important part in giving birth to solemn thoughts, together with the height and size of the three enormous pilasters which alone support the roof—the lofty arches, the vast depth and gloom of the aisles, the intensity of the shade, the deep silence made still more impressive by an occasional foot-fall—all would combine to proclaim this a house of prayer, and nothing else; a Temple in the fullest and most unequivocal sense of the word, offering to the old and the broken-spirited, to the infirm and to all who sought it in prayer, an assurance of tranquillity, consolation, and peace! Having enjoyed my oft-repeated visit, and purchased a large supply of Eau de Cologne from the Farina gegenüber dem Julichs Platz, (and don't you believe that the others make it near as good), I got in the train for Munich and for Vienna. I think I see a smile, slightly perhaps savouring of a sneer, from some of my readers of the masculine gender, at my purchase of a large supply of Eau de Cologne; but just let them hold hard, till they shall have endured the trials of hot winds and dusty roads in the daytime, stuffy cabins and the ordinary accompaniment of flea invasions and other entomological attacks in the night-time; and then if they have the luck to have any of it with them, they will discover the use of Eau de Cologne in allaying pain and irritation. Travellers in all Eastern countries should have with them a supply of good Eau de Cologne, not for scenting their pocket- handkerchiefs only, but principally as a remedy. Some people suffer
47.
more, some sufferless from insect attacks; but I have seen a man, a strong, stout, brawny Britisher, set nearly wild by flea-bites, and I shall never forget his appearance, as he stood before me one morning, after passing a restless night in a very wild region in the South of Europe, like a patient with small-pox, and scratching away at himself for bare life. I am sure he would have been in a high fever that night, had I not bathed him with a mixture of equal parts of Eau de Cologne, laurel water, and sal-volatile. So don't forget it, kind reader, if ever in your travels you are likely to be in countries infested with insect tribes; whatever their nature may be, whether the mosquito which flieth, the flea which hoppeth, or t'other thing which crawleth, my nostrum will be found a sovereign remedy against them all. Although the Vienna Exhibition was fully open, and that numbers were flocking from all parts to that most charming capital, which has so justly acquired the epithet of "le Paradis des Hommes," I was fortunate in having but one companion in the train all the way, and thus we both were enabled to extend our limbs and sleep as comfortably as in our beds. It is wonderful the amount of comfort one can obtain through life by the judicious distribution of a few cigars accompanied by a little silver! At Vienna, I went—as I always do—to the Archduke Charles' Hotel; a little old-fashioned, perhaps, but unquestionably the best hotel in Vienna, and where the cooking is always undeniable. During my short stay, I went every day to the Universal Exhibition—the world's fair! but don't be afraid that I mean to weary you by dragging you with me through those confusing avenues of "all sorts," where nothing that was wanted could be found, and everything we wanted not was sure to be everlastingly obtruding itself before our eyes.
48.
I confess thatthe Vienna Exhibition disappointed me; whereas the Paris one of 1867 left me nothing to desire; and all owing to the want of order and system in the one instance—while in the other, the arrangement was so perfect that there was not the smallest difficulty in getting at anything one wanted to find out. But if the exhibitional department was less perfect in its arrangement at Vienna than at Paris, the gardens and the outside accessories were far more beautiful at the former than the latter; while Strauss's delightful band always afforded an hour's luxurious enjoyment in the cool of the afternoon, till the fearful braying of the steam trumpet, (they called it a Telephone, I think) drove one out into the Prater. Then the restaurants and cafés of the different Nationalities were so well got up and so picturesquely scattered about the Gardens, as were also the several buildings characteristic of the different Nations, and among which was pre-eminent for elegance of form, design, and execution, the kiosk of the Pasha of Egypt. And then the Viennese ladies! I know I should have mentioned them the first, I confess it; confiteor, mea culpa, mea maxima culpa, but, gentle reader, it was from sheer diffidence! I did not know how to approach the subject, I felt myself totally incompetent, and indeed I do so now! To say that at Vienna there are more lovely women to be seen than in any other city in Europe, is not saying one half. There are loads of pretty women to be seen in Dublin of a fine Sunday afternoon, especially among the middle and lower classes; but at Vienna they are not only lovely, but terribly attractive, and winning, and seductive; there are none like them anywhere else! In the fine arts department there were many beautiful things to be seen; but as I promised not to drag the reader round the World's Fair, I shall keep my word, and shall only call his attention to two statues which greatly attracted me, one was a bronze figure of a
49.
Hindoo charming acobra, the other a Negro running away, both figures perfectly alive! I went twice to the opera, once to hear Meyerbeer's "Africaine," which disappointed me; and once to see a grand ballet, I think it was called "Eleonora," which did not. I had not been for several years at Vienna, and had, therefore, not seen the new Opera House. I was greatly struck with its size and beauty; it is unquestionably the finest theatre in Europe, and the arrangements are perfect. But Vienna is now undergoing such a process of transformation, and to such an extent, that in a few years those who knew it ten or twelve years ago will be utterly unable to recognise it. Even now it is one of the finest capitals in Europe, but at the rate it is progressing, it bids fair to surpass in a short time every other city, when the Viennese will really be able to give utterance with truth to their old saying, "Gibt nur eine Kaiserstadt, gibt nur ein Wien!" After a very delightful week in Vienna, which seemed indeed far too short a time to bestow upon the most enjoyable capital in Europe, I took my passage in a steamer to Pesth, starting at six a.m., and arriving at my destination at about the same hour in the evening. The steamer was a very fine one, the accommodation excellent, the cuisine not good, but then I had been terribly spoilt at the Erz-Herzog Karl; probably had I been at a worse hotel, I would not have found so much fault with the cookery on board the steamer. The company on board was worse than the cookery—in all my rambles I don't think I ever met so unprepossessing a lot. The large steamers that navigate the Danube don't come up to Vienna, but lie off the Island of Lobau, to which passengers are carried in a smaller steamer. The morning I started was drizzling and chilly in the extreme, in marked contrast with the weather of the previous week, which had been intensely hot; and when I sat down on the deck of the little steamer which was to take me down a
50.
branch of theDanube to the main steamer, I was glad to avail myself of my top-coat and rugs. In a short time we reached the larger vessel, and, having all got on board, we started at a good round speed. From Vienna to Gran, the Danube is uninteresting so far as scenery is concerned. Its enormous volume of muddy water, wider than the Thames at Westminster, though still upwards of nine hundred miles from its entrance into the Black Sea, flows through a vast flat country; an interminable front of sallows and alders on the one side, and an interminable plain on the other, dotted all over with countless herds of white cattle with long black horns like the Tuscan oxen, and endless troops of horses; and as I gazed on the mighty flood of turbid waters, the old Italian nursery rhyme came back to my memory. "Tre Ombroni fanno un Arno, Tre Arni fanno un Tevere, Tre Tevere fanno un Pò, E tre Pò di Lombardia Fanno un Danubio di Turchia." We passed by Pressburg where the two sides of the river are united by a bridge of boats. We only remained a short time and I had no opportunity of going ashore, so that I could form but a very inaccurate opinion of the place; it seemed to me from its outward look as not now prosperous, but had quite the appearance of having seen better days. After a time we came to Komorn, the celebrated fortress; if I had not been told, "There is Komorn," I might almost have passed it without observing it, so protected from sight are its bastions by the immense earthworks in front of them. Still down we steamed, and still the same country right and left met our view, till we came to
51.
Gran, the seatof the Prince-Primate of Hungary, perhaps one of the wealthiest prelates in the world, possessing no less an income than £90,000 per annum. Here the scenery began to improve; the Cathedral of Gran, though in itself unclassical, and one that in any other place might be passed by unnoticed, yet served to relieve the monotony of the view. The river, which up to this had flowed through boundless plains, became suddenly contracted, and consequently swifter as the high lands approached the edge of it; and now with every revolution of the paddles the scenery improved, till on reaching Vissegrad it became absolutely lovely. Instead of the interminable plains, we now had precipitous mountains on either side, some clad with forest down to the water's edge, some bare, ragged, and rocky, but all lovely, quite equal to the finest parts of the Rhine, not even lacking a Drachenfels in the beautiful ruins of the ancient castellated palace of the Kings of Hungary, the favourite retreat of the learned Matthias Corvinus. Nature has done everything to beautify this favoured spot, but man, as is too often the case, has done his best to mar it. At the foot of the cliff, the top of which is crowned by the ancient residence of the Kings of Hungary, on a beautifully wooded spot between the mountain and the rushing Danube, some enterprising German has erected, horribile visu, three villa residences, in the correct suburban style, a few yards distant from one another. Regardless of expense, everything about them, including themselves, is radiant with white- wash, except where green paint asserts its place. At first I thought it must be an hotel or pension, with two succursales; but no, the skipper assured me they were country houses, and seemed astonished when I said the man that built them deserved to be hanged in front of them; he could not comprehend me, he thought them lovely!
52.
Often during mysubsequent travels I thought of that lovely country between Gran and Vissegrad; such exquisite scenery, so diversified; such a combination of rolling pastures, of glorious hills clad with forests, backed by rugged mountains, with that grand old Danube rushing through the midst; such shooting and fishing, all in a compact locality, and only four hours by rail from Vienna; such a spot for a country residence could scarcely be equalled, and certainly not surpassed. If it were within ten hours of London, what a fabulous price it would command! but here no one seems to have placed any value on it since the days of Matthias Corvinus. After going through this gorge, the Danube spreads itself out again, and the scenery becomes tame and uninteresting, and continues so till one reaches Pesth, where I arrived somewhat later than I expected.
53.
CHAPTER III. PESTH—HOTEL UNGARIA—BUDA—STORYOF AN ARTIST—PROSPERITY OF THE CITY—NEW BRIDGE OVER THE DANUBE—ST. MARGUERITE'S ISLAND— ANCIENT ROMAN BATH—CONDITION OF HUNGARY—FIELD FOR THE JUNIOR BRANCHES OF THE UPPER TEN THOUSAND—KEEPING UP APPEARANCES—THE TERMINATION OF TURKISH MISRULE—FUTURE OF THE DANUBIAN PRINCIPALITIES. DROVE to the Hotel Ungaria, to which I had been recommended, and where a most comfortable apartment and an equally good dinner gave me an avant-goût of a comfortable night's rest, in which I was no wise disappointed; and I can safely recommend the Ungaria as one of the finest and most comfortable hotels in Europe, without at the same time being extravagant in its charges. The only drawback I found was with the person of the porter, a most respectable man no doubt, but he could not speak either French or English; and I had to carry on all my consultations respecting my intended future progress with the hall-porter of the "Königin von England" hotel, close by. If that man could only be installed at the Ungaria, that hotel would be as near perfection as possible. The windows of my bedroom at the Ungaria opened out on a balcony which gave me a splendid view of the "blue Danube," which, however, I never saw of any other shade but mud colour. Across the river, and just opposite, I could see the ancient city of Buda, with the
54.
royal residence infront, and a little to the left, on the top of the hill, the celebrated fortress which played so important a part during the last Hungarian civil war. A little to my right was the grand suspension bridge, guarded at each end by two colossal couchant lions, about which the following improbable anecdote was related to me. The artist who executed them forgot to put tongues into their mouths, to loll out in proper heraldic fashion, and when the defect was pointed out to him as the lions were uncovered, he took it so to heart that he at once put an end to himself by plunging headlong into the river! Now when "le grand Vatel" committed suicide, because the turbot did not arrive in time for the dinner of the Most Christian King, there was some show of reason in the act, Vatel's credit was in some degree pledged to that dinner; but not one man in ten thousand would have noticed whether these lions had tongues or not. Pesth seems, like Vienna, to be undergoing a process of rebuilding, and that on a scale of considerable magnificence. I was told that its commerce was daily increasing, and, certainly, to judge from the immense number of vessels moored in the river, the ceaseless passing up and down of immense steamers, the piles of merchandize, and the constant bustle on the quays, a very considerable amount of business must be done there. The grand suspension bridge which spans the Danube being found insufficient for the increasing traffic, a new one is in process of construction, to be built of iron on piers, and not a suspension bridge. It is to cost an immense sum, and will require to be well protected against the action of the ice on the one hand, while on the other it may become the source of considerable danger to the low land in its neighbourhood by arresting the free passage downwards of the ice, if not well looked after. I went to see the works at the central pier, and remained there some time watching the men at the bottom of the immense caisson out of which a donkey engine was incessantly
55.
pumping water; outsideit, the river was running like a mill race at not less than eight miles an hour, and I was assured that the depth at that spot was fully forty feet. After visiting the works at the new bridge, I went to St. Marguerite's Island, on which is a park beautifully laid out, and which forms one of the favourite promenades of the pleasure-loving inhabitants of Pesth. As it can only be approached by boat, it is frequented only by pedestrians; but in order to cater for all tastes and gratify those who enjoy a jaunt, there is a tramway running the whole length of the island. There are also some capital restaurants, and several bands play every evening in fine weather. There is another park on terra firma, an imitation of the Prater at Vienna, but it is small and shabby. There were a good many people strolling about it when I went, but I did not see even one middling- good turn-out, and though one constantly hears of the beautiful horses and rare horsemanship of the Hungarians, I was doomed to be disappointed in both cases. Crossing over the suspension bridge one gets into the old town of Buda or Ofen, in which are situated the Royal residence, the Government offices, and some of the palaces of the native magnates. There is a fine street by which one can drive to the upper part of the town, which is considerably above the level of the Danube; but for pedestrians there is an easy, cheap, and quick method of getting to the summit, by means of a small counterpoised railway, which carries one up and down very rapidly at an exceedingly moderate rate. There is a fine view from the top, and several fine old palaces, but the most interesting thing in the town of Buda is the old Roman bath erected over some sulphurous springs, celebrated for the cures they perform. It is in exactly the same condition as in the days of
56.
ancient Rome, andconsists of a large vaulted apartment lit by a circular opening in the centre of the cupola, and containing a large hexagonal piscina with an ambulatory all round. None bathe there save the lower classes—men, women, and children promiscuously; in the immediate neighbourhood, however, there are some very well appointed baths which are considerably patronized, and bear a high reputation for the cure of skin disease. From all I could collect during the brief stay I made at Pesth, Hungary in general must be in a very progressive condition; and from the numbers of agricultural machines and implements, all of English construction, which I saw everywhere stacked upon the quays, not only at Pesth but at many other stations on the Danube, including large numbers of steam-thrashing and winnowing machines, a vigorous attempt is evidently being made to exploit the unbounded fertility of perhaps the richest soil in Europe. Land, however, is still cheap in Hungary, probably in consequence of the extreme love of pleasure of its inhabitants, who preferring to spend their days in the society of Vienna, Paris, or Pesth, draw exorbitantly on their revenues, till at last compelled to sell their lands in order to meet their engagements. Nice estates within twenty miles of Pesth, with good substantial dwelling-houses, and all the necessary offices for farming, with varied soil, vineyard, pasture, tillage, and forest, can be had sufficiently cheap to ensure a clear return of five per cent, free of taxes, for the capital laid out on them! A vast number of the agricultural community in Hungary are Jews, and it is perhaps the only country in Europe where we find the children of Israel as tillers of the soil; and I was assured by many in Pesth that they make by far the most satisfactory tenants—though naturally they require looking after occasionally, as well as their soi-disant Christian brethren. When one reflects on the countless acres of the richest land in creation, which to a great extent are still unoccupied and
57.
uncultivated in theeastern and south-eastern regions of Europe, one cannot help regretting that some of our surplus population do not try a venture in those countries. I am thinking principally of that most unfortunate and ill-used portion of society belonging to the upper classes, and which, from circumstances beyond its control, is suffering from positive want in its struggles to keep up a respectability as necessary for its existence as the very air it breathes. The labourer, the artisan, the skilled workman are well off at the present time in our country; wages are very high and the friendly societies, to one of which almost every workman belongs, provide for them amply in cases of sickness, and in some cases even contribute something to the family when the illness terminates in death—not to mention the numerous hospitals and asylums, all open to the labouring classes, but which are all virtually closed to those I am now speaking of. The working classes, with few exceptions, are all well off at present, and require none of our sympathy except when in affliction, when the richest and poorest come to the same level. They can afford to supply all their wants out of their wages, and lay out one fifth, and in many cases one fourth, and even one third (I am assured by good authorities) in drink, for the gratification of the only pleasure which they are capable of enjoying; for proof of which the police reports throughout the country will bear ample evidence. But I will tell who really deserve all our sympathy and all our aid, the junior branches of our upper ten thousand—the families of officers, poor clergymen, poor lawyers, &c., &c., all struggling for dear life against difficulties of every kind; those are the classes who claim the greatest share of our sympathy, and to whom the regions above mentioned offer advantages unequalled any where else. I remember when the Canterbury settlement was established in New Zealand, it was intended in a great measure to provide for the
58.
classes I havealluded to above; but the distance was too great, the mere cost of going out was a most serious drawback, at the very least ten times the amount required to land one bag and baggage in the centre of Hungary, or better still in Servia, among some of the most beautiful scenery in the world, the richest soil, the best climate, and the finest fishing and shooting that could be desired, where game laws and river preserves and licences are still utterly unknown. I hate croaking; still, if one hears rumbling noises underground for any space of time, one is justified in apprehending an earthquake. For several years I have been hearing these subterranean noises, and year after year they have become more and more threatening, and the earthquake must come at last. But as a volcanic eruption, acting as a safety valve, often saves a country from the effects of a physical earthquake, so the timely exodus of an excessive population may save a country from a moral one. By the very nature of my profession, I have innumerable times been willingly or unwillingly let into the secrets of the private affairs of scores of families; and I have watched with perfect dismay the misery, the poverty, the utter wretchedness that were screened from the eyes of the world by the decent exterior which was kept up in order to preserve appearances. If with Asmodeus we could but lift up the roofs of a few thousands of houses in these prosperous islands and see the difficulties, the make-shifts, and the make-believes which are resorted to, and that in many cases where one would least expect them, it would make our very hearts bleed at all the anxiety, all the wretchedness, all the scalding tears which would be disclosed—all brought about by that great delusion "keeping up appearances." Well, all this living under false pretences, which is the distinguishing characteristic and the great evil, the real "social evil" of the present
59.
time cannot goon for ever. It is an evil of long standing, no doubt, but it has gone on increasing from year to year, like a falling avalanche, with constantly increasing velocity. The earthquake must come at last, if not averted by an emigration en masse of those educated classes to which I have alluded above; and the best, finest, healthiest, most fertile, and most accessible country, outside the British dominions, I hold to be, roughly speaking, that tract of Southern Europe bounded on the North by the Saave, on the South by the Bosphorus, on the East by the Danube, and on the West by the Adriatic. "But, my dear Sir," I think I hear some reader say, "that is Turkey in Europe!" No doubt it is, but the Turks won't be there for ever, their time is nearly run out; the period of their wretched misrule over the Christian populations of Europe is nearly accomplished, and I still hope to live long enough to see those barbarous hordes recrossing the Bosphorus into Asia Minor, on their way back to the Steppes of Khiva and Bokhara, from whence they originally emigrated. They have ever shown themselves irreclaimable barbarians throughout. Look at the present condition of European Turkey, after centuries of Ottoman dominion; contrast it with the nascent state of Roumania, which only quite lately succeeded in shaking off its Moslem chains. Let us look at both countries, as they present themselves opposite to each other on the banks of the Danube. On the left bank of that river we have Giurgevo in Roumania, the port of Bukharest, where, notwithstanding centuries of slavery and misgovernment, the natives, now under the government of an enlightened Christian Prince, are all activity and progress—while on the right bank at Rustchuk, just opposite, in dark contrast to the Christian, who is trying to turn to account all the advantages of his country, the indolent, uncivilized Turk is still lazily dozing away, leaning against his ancient painted and bedizened araba, drawn by a pair of patient oxen, waiting for the chance of some solitary, silent traveller!
60.
A new erais dawning, however, over these south-eastern regions, but much of their prosperity and future happiness may depend on the model they will propose for themselves in their efforts at civilization; whether the brilliant glitter of Parisian veneering and varnish, or the less attractive, but more solid advantages of British institutions. A great future is before the Danubian Principalities, may they use their opportunities with wisdom, and may they prosper!
61.
CHAPTER IV. STEINBRÜCK—THE SÖMMERING—FIRSTVIEW OF THE ADRIATIC—TRIESTE— SHOCKS OF EARTHQUAKE AT BELLUNO—AUSTRIAN IRONCLAD 'LISSA'— CAPTAIN R. BURTON—FLYING VISIT TO SAN CANZIANO—SUBTERRANEAN COURSE OF A MOUNTAIN STREAM—THE KARST—WILD SCENERY—A THUNDER- STORM—CHURCH OF SAN CANZIANO—STUD FARM. HAT odious and useless mediæval institution, the quarantine, having barred my passage into the Lower Provinces of the Danube, I determined to go to Trieste, then proceed by sea to Constantinople, and thence to the Caucasus, but it was written differently in the book of Fate! The line to Trieste was full of interest; during the first portion of the journey I passed quite close to Lake Balaton, celebrated for its fish, and then after traversing some wonderfully rich plains, dotted here and there with patches of forest, and covered with herds of cattle, horses, and geese, which are kept here in vast numbers for the sake of their feathers, arrived at Steinbrück at one p.m., where I dined. Here, at the junction of the Saane and the Saave, the scenery became truly magnificent; we had been for some time following the banks of the Saane, and the mountains had been getting closer and higher with every mile we made, till at last they actually came down to the river, allowing a bare passage to the railway which followed its every bend.
62.
Having finished ourmid-day meal at Steinbrück—where the Pesth line joins on to that miracle of engineering, the celebrated railway between Vienna and Trieste—we resumed our journey, the scenery retaining its grand features, till having topped the Sömmering, we came on to the desert Karst and got our first peep of the salt water—the glorious Adriatic. Nothing could exceed the wild grandeur of the country on both sides of the railway, as the engines (for we had two of them) slowly panted up those steep inclines, winding in and out through the gorges of the Sömmering, now plunging into a tunnel to traverse the heart of a mountain, and now crossing a viaduct between two cliffs, over a precipice hundreds of feet in depth. Once at the top, our pace increased considerably, and by eight o'clock I found myself comfortably installed at my hotel at Trieste, on the evening of the 29th of June. After a most refreshing night, I descended the next morning to the café on the ground floor of the hotel, and then heard for the first time of the severe shocks of earthquake at Belluno and its neighbourhood, which had been felt even in Trieste. Several lives had been lost, and one church nearly shaken to the ground. After breakfast I went to pay my respects to our excellent consul, Captain Burton, and then hearing that the Austrian ironclad "Lissa" was outside the harbour, I took a boat and went to have a look at her. She is a fine vessel with a long projecting prow, and looks well in the water. Having sent up my card, I was received and shown over the ship by Lieutenant Count Petruski, who was most kind in pointing out every thing of interest connected with it. I think he said she mounted 12 rifled fifteen-ton guns of our Woolwich Infant type, and was furnished with a galvanic apparatus, by means of which the captain could fire a whole broadside at a time. Although she was only in after a cruise, and consequently not in the best of trim for exhibition, I was much gratified by all I saw. The men were a very fine set of fellows, the state cabins and officers' cabins
63.
particularly neat andnice, and should these lines ever fall beneath the eye of Count Petruski or any of his brother officers on board the "Lissa" I beg them all to receive my warm thanks for their kindness to me that day. I spent a couple of very pleasant hours on board, and as Count Petruski spoke excellent English, it made our interview all the more agreeable.[1] Trieste is anything but an interesting place; though a couple of days may be spent pleasantly enough visiting the neighbourhood, especially if one has the advantage of the acquaintance and company of our consul, Captain R. Burton; the Burton of Harar, of Mecca, and of Medina; the facile princeps of modern travellers and pleasant companions. Why is Captain Burton kept at Trieste? It is not a difficult post, nor one requiring a man with exceptional qualifications; and it does seem a misapplication if not a waste of force to keep a man like Burton at Trieste, when he could be of so much greater use elsewhere. The thorough and intimate knowledge that he possesses of Oriental character, his perfect mastery of Arabic, together with the knowledge he has of Persian and scores of other languages, not to mention the experience he has acquired of Oriental affairs, customs and idiosyncrasies, all go to point him out emphatically as the right man in the wrong place at Trieste. I spent some very pleasant hours in his company during my short stay in that city, and shall never forget the kindness I experienced both from him and la bella Contessa, his most charming and accomplished lady. Thus far, my observations have been of a strictly selfish nature. I know Captain Burton's capabilities, I feel that he is utterly thrown away where he is, and I want a quid pro quo for my money— consequently I want to see him in some post where his talents and exceptional qualifications may be of some profit to me. The reader will perceive that I am strictly selfish and utilitarian, and that in
64.
writing as aboveI have not been led away by sentimentality in any shape. Had I been in the opposite vein, I could have said, I met at Trieste Captain R. T. Burton, who undoubtedly is the greatest of living travellers, and also second to none in that great phalanx of explorers, who from time to time have devoted their lives to carrying civilization to the most remote corners of the earth. He opened up Eastern Africa, and most probably discovered in Lake Tanganyika the mysterious sources of the Nile. He directly opened up the path and led the way which was subsequently trodden by Speke, Grant, Stanley, Cameron, and others; indirectly he pointed out the way to Baker, Schweinfurth and Gordon. To Richard Burton then is due the discovery of this New Africa, this great Lake Region, so fertile and so rich in the centre of a continent which fifty years ago was believed to be one vast uninhabitable desert. What has been his reward? He has been made consul at Trieste. Here is an inducement to our ardent British youth! I hear there is some talk of making him a K.C.B.; for myself, I wouldn't give a roll of ginger-bread for the distinction; however, let him have it by all means, but let us see him also removed to some more useful sphere of action where his exceptional talents and his great knowledge of Oriental languages may be of service to us. Let him be sent to Africa again—to Morocco for instance—at the first vacancy. Having still to wait a couple of days for the departure of the steamer which was to take me on my trip down the coast of Dalmatia, I employed my time in paving a flying visit to San Canziano, where a good-sized river, after meandering down a deep ravine like any other Christian stream, suddenly plunges into the bowels of the earth, and after a mysterious course of many miles, reappears again at the surface under a different name, previous to losing itself in the Adriatic. The little hamlet of San Canziano is about twenty miles from Trieste, it consists of a very small and meanly built church, with a
65.
good campanile however,with two sweetly-toned bells—why is it that ours are always so unmusical and woody?—a small wretched Presbytery, a roadside pot-house where nothing could be got for love or money, and half a dozen dilapidated houses. The drive however, was very pleasant, for the weather was warm and at the same time cloudy, so that we were never inconvenienced by the sun. The road, on leaving Trieste, goes by easy windings over a mountain clothed with oak, so beautifully kept, that it gives the idea of driving through some private park. On reaching the top we came into the open, and had a glorious view of the Styrian mountains on the one side, and the Adriatic on the other. After driving for a short time on the level, we again commenced ascending and soon got into the "Karst," as it is called; a wild barren tract where little or nothing appears to grow, and where rocks and stones seem to have rained down from heaven, not unlike some other spots I visited subsequently in Dalmatia, and notably in Montenegro. But this bleak and barren spot owes its absolute desolation, not so much to the rocky nature of its soil, as to the Bora, a north-east wind, which often sweeps across it with the force of a West Indian hurricane. In many places on the road, traverses of immensely thick stone walls had been erected for protection against the fury of the wind, but notwithstanding all, the Karst is sometimes impassable when the Bora blows in real earnest, and heavy-laden waggons which have tried to cross it at such times, have been turned over and over like "leaves in Autumn weather." After travelling for some short time along this elevated plateau, we again began to descend, and soon reached our destination, where, having eaten the lunch I had brought with me, I started on foot, under the guidance of a native who could speak nothing but Styrian, to seek the mysterious river. In less than half an hour's walk, I found myself on a grass- covered plateau of some miles in extent, fringed in the distance by lofty hills, dotted with clumps of fir trees, and after a few minutes
66.
more walking inan easterly direction, I suddenly came on a perpendicular precipice, upwards of five hundred feet in depth, which completely barred my further progress. The cliff on which I stood rose in a narrow valley, or glen, or cleft, as if the crust of the earth had cracked here for a few miles. This cleft, nearly of uniform depth, was not of uniform width; in some places it was so narrow that the smooth river which glided through it completely filled it from side to side, while in other places a sufficient strip of soil remained between the river and the cliff to admit of some amount of cultivation, and here and there a cottage. This strange cleft, or valley, or crack in the plateau through which the river flows is of a most irregular outline, going zig-zag, in and out, just like the cracks one sees in a dried up pond at the end of a hot Summer in England. I was standing where this precipitous crack barred the way, by running exactly at right angles across the path, and here right under me at a depth of about five hundred feet, the river which could be seen coursing from a considerable distance at the bottom of the cleft, suddenly leapt into a cavern and disappeared beneath my feet. Having made a rapid sketch of this extraordinary landscape—or, more correctly speaking, having tried to convey on paper some faint idea of what the place was like—I again followed the guide, who now, turning his back on the precipice, led me in a westerly direction, and brought me in a few minutes to the brink of a fearful- looking circular chasm, about fifty yards in diameter, with precipitous rocky sides, and from the bottom of which could be heard the distant roar of the river rushing among the rocks. The guide threw some large stones down this yawning gulph, disturbing some thousands of rock-pigeons who build their nests in the nooks and crannies of the rocks, and having timed the fall of one of these stones by listening for its splash in the subterranean river, I noted about seven seconds as the time it took in falling.
67.
I now accompaniedthe guide through the little hamlet of San Canziano, and still going westward came just beyond the village on another chasm, of oblong form, about six hundred yards one way, and three hundred and fifty yards the other way, while in depth it was no more than about fifty yards. It looked to me as if this opening had been made by the subsidence or falling-in of the roof of some cavern, of which the limestone rock of these mountains, as well in Styria as in Dalmatia is so full. The sides of this depression were not precipitous except in some places, and an easy descent led me to the bottom, across which stretched from side to side a fantastic ridge of rock pierced by a natural arch about the middle, and under which an opening in the rock gave entrance to another cavern, through which anyone desirous of exploring it could without much difficulty, but at the cost of some fatigue and the risk of some falls, descend by a series of about six hundred high and slippery ledges of rock to where again the river makes its appearance after its subterranean course. As the day was pretty well advanced, and as the weather, which had been cloudy all the morning seemed now to be threatening rain, I thought it wisest not to venture on going further, although the guide had provided himself with candles for the descent. So I scrambled up the sides of the chasm, and was making for the roadside inn where the carriage was waiting for me, when the storm-clouds, which had been gathering thicker and thicker for some time, broke out at last into such a deluge of rain, accompanied by thunder and lightning, that I was glad to take refuge under the archway of the belfry of San Canziano, and from thence into the church itself, the door of which was opened for me by a queer little old dried-up chip of a sexton. I am sure he said to me, "Pray take shelter in here from the rain," though as he spoke Styrian I could not understand a word, but his looks and gestures were as eloquent as words. Having walked
68.
into the littlechurch, first taking off my hat, the little sexton became quite eloquent, and pointed out with evident satisfaction to every part of the chapel, which was poor and desolate in the extreme. Four white-washed walls, a wretched altar piece of wood painted in a few gaudy colours, and a crimson damask baldachino in tatters, which, stowed away in a corner, served to shelter the "Santissimo" when carried about in procession, two or three benches, a confessional box, and a lighted lamp hanging in front of the altar, constituted toute la baraque! but the poor little old man seemed delighted with himself and everything around him, and kept repeating in a shrill voice the only Italian word he apparently possessed "Bella," "Bella," to which I responded as in duty bound, "molto bella," and I trust I may be forgiven the cram; for I never told a bigger one in all my life! The floor of this little church was formed of large flag-stones, in some of which iron rings were inserted, while in others there only remained the marks of where rings had formerly been; some had inscriptions, and I should have been interested in hearing something of the ancient tenants of these graves, but here the sexton and I came completely to a dead lock. "Bella" could serve my friend no longer, still he understood perfectly what I required, so when he sat down on a bench, pointing to me to do the same, I complied at once, and all the more willingly as the rain was still coming down in torrents. The old fellow then commenced, and, pointing with his skinny finger to the central slab, entered at once into what, I presume, must have been a full, true, and complete history of the tenants of that grave, descanting probably on their virtues, and dealing gently with their faults; but alas! I could not understand one word. At last, I suppose the same thought must have struck "Old Mortality," for he suddenly stopped and bursting into a shrill, unearthly, and most discordant laugh, pointed to the sky which was now clearing, and
69.
held out hispalsied hand, when I discovered he knew another word, not Slave, nor Italian, but this time German, "Geschenk!" I gave him the only bit of silver I possessed, an English sixpence, and left him seemingly contented. The clouds had all melted away, and the sun shone brilliantly when I left the little roadside tavern of San Canziano to return to Trieste; but, as I wanted to visit a stud-park which the Emperor of Austria keeps in this part of his dominions, we took another route on my return journey. The country we now drove through was prettier than what we had traversed in the morning, and the road passed through some fine oak woods, which constantly prompted one to look out for a mansion, the country appeared so park-like—but in vain. After a drive of an hour or so we came to the stud-farm, a collection of large buildings, consisting of several dwelling-houses, a spacious riding-house for exercising the horses in severe weather, three large stables intended to accommodate three hundred mares, and one lofty vaulted stable fitted with nice large loose boxes in which were kept the sires. The mares were all out at grass together with their foals, so that I did not see them, as I should have had to drive some miles in a different direction, and turn my back on Trieste in order to visit them. The sires I did see, but as they were not led out I could not form as accurate an opinion of them as I should have wished. They seemed, however, small, and not exactly the style of horse we would select in this country with a view to supplying our cavalry. The loose-boxes were commodious and the stable was well- ventilated; the weather being extremely hot the windows were closed with tatties, which served the double purpose of keeping away the flies, which always seek the light, and keeping the stable cool. The stable was fairly clean, but the grooming did not come up to our ideas. On the whole I was disappointed, and as for the
70.
produce, I shouldthink that nothing but the very lightest of light cavalry horses could be expected from them. We returned to Trieste by nine o'clock, coming by the old post- road from Vienna, and passing by that wonderful quarry of limestone slabs, perhaps the largest in the world.
71.
CHAPTER V. THE "SANCARLO" AND HER PASSENGERS—A DALMATIAN'S REMARKS ON THE PRESERVATION OF HEALTH IN INDIA—DALMATIAN DIGGERS FROM AUSTRALIA —COAST OF ISTRIA—PIRANO—CATHEDRAL OF PARENZO—ROVIGNO—POLA— THE AMPHITHEATRE—PICTURESQUE SIGHT—GIOVANNI ASTONISHED— MONTENEGRIN COSTUME—ZARA—EXTREME HEAT. n the 2nd of July I was up betimes. I had taken my place for Zara on board the 'San Carlo,' a small coasting steamer which trades down the Dalmatian side of the Adriatic, going in and out among that archipelago of islands which fringe the coast of Dalmatia from the mouth of the Guarnero to the entrance of the Gulf of Cattaro. It was a small, slow, and dirty little steamer, but it stopped everywhere going on its way, and that was just what I wanted. Small as the vessel was, we had plenty of passengers, and a strange lot they were. We had two Capuchin monks going to Ragusa, one of them a most interesting man of whom I shall have more to say by and by; his lay brother, a simple, ignorant monk, and no more. We had a tall, handsome Dalmatian from Spalato, returning home to end his days in opulence and comfort after spending twenty years in India, where he had accumulated an independence which in Dalmatia will be considered a large fortune. He spoke English remarkably well. Being struck by his hale and
72.
robust looks, Iasked him how he had managed to preserve his health so well after residing for twenty years in India. "Many of them," added he, "in unhealthy localities." "Simply by not drinking," he answered. "I don't mean to say that I was a water-drinker—not at all, for I believe that water-drinking is nearly as bad as spirit- drinking, and indeed I think I have observed that those who were 'teatotallers' died even sooner than drunkards. But I never drank anything before breakfast, I drank nothing but good, full-bodied claret, and I never took more than two bottles of it a day, and seldom so much; I smoked, but always in moderation, and I never had a day's illness during those twenty years. India is not a bad climate, it is the reckless habits of Europeans that make it apparently so." We had two other Dalmatians from Sebenico, who also were returning home after residing many years abroad. These two had been in Australia; one had been a digger, and seemed the reverse of well-off; the other had kept a store at some gold-diggings, and had apparently made plenty of money. Both spoke English well, and the last one brought with him from Australia an Irish wife, who had emigrated to the Antipodes all the way from Lurgan. She was a fine comely young woman of about twenty-six, and was overjoyed at finding I knew her native place. In the afternoon I made some tea in my portable kitchen, and gave her a cup of it with some preserved milk, which she declared the most delicious thing she had tasted for many a long day. The rest of our passengers consisted of country people returning to their homes along the coast of Istria and Dalmatia, after having been to Trieste to dispose of the produce of their lands. As the clocks struck five, we steamed out of Trieste on one of the finest mornings that could be imagined. The sea was as smooth as a mirror, and of the most intense blue. How often we stopped as