Book Image

Modular Programming in Java 9

By : Koushik Srinivas Kothagal
Book Image

Modular Programming in Java 9

By: Koushik Srinivas Kothagal

Overview of this book

The Java 9 module system is an important addition to the language that affects the way we design, write, and organize code and libraries in Java. It provides a new way to achieve maintainable code by the encapsulation of Java types, as well as a way to write better libraries that have clear interfaces. Effectively using the module system requires an understanding of how modules work and what the best practices of creating modules are. This book will give you step-by-step instructions to create new modules as well as migrate code from earlier versions of Java to the Java 9 module system. You'll be working on a fully modular sample application and add features to it as you learn about Java modules. You'll learn how to create module definitions, setup inter-module dependencies, and use the built-in modules from the modular JDK. You will also learn about module resolution and how to use jlink to generate custom runtime images. We will end our journey by taking a look at the road ahead. You will learn some powerful best practices that will help you as you start building modular applications. You will also learn how to upgrade an existing Java 8 codebase to Java 9, handle issues with libraries, and how to test Java 9 applications.
Table of Contents (19 chapters)
Title Page
Credits
About the Author
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

Advanced services


The services concepts covered so far should address a lot of typical use cases, but there are a few additional features and concepts that might come in handy in certain special scenarios. We'll look at a few such concepts in this section.

Supporting singleton and factory providers

Suppose your service instances cannot be created simply by a constructor. What if you need to reuse instances, maybe to have a singleton provider instance? Or maybe execute some logic whenever a new service instance is created? There is a handy feature of services that lets you create factory methods to get service instances. All you need to do is add a method with the name provide() in your provider classes. The method needs to be a public static method and it shouldn't take any arguments. Also, the return type should be the same as the type of the service being provided. If the ServiceLoader sees this method, it calls it, and uses the return of the method as the service instance. If it doesn't...