




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































Advanced java i
Advanced java ix
Learning the basics of Java is easy. But really delving into the language and studying its more advanced concepts and nuances is what will make you a great Java developer. The web is abundant with “soft”, “cheap”, “low end” Java tutorials, but what it is missing is material to really take you to the next level. This book is designed to help you make the most effective use of Java. It discusses advanced topics, including object creation, concurrency, serialization, reflection and many more. It will guide you through your journey to Java mastery!
Advanced java x
Andriy completed his Master Degree in Computer Science at Zhitomir Institute of Engineering and Technologies, Ukraine. For the last fifteen years he has been working as the Consultant/Software Developer/Senior Software Developer/Team Lead for a many successful projects including several huge software systems for customers from North America and Europe. Through his career Andriy has gained a great experience in enterprise architecture, web development (ASP.NET, Java Server Faces, Play Framework), software development practices (test-driven development, continious integration) and software plat- forms (Sun JEE, Microsoft .NET), object-oriented analysis and design, development of the rich user interfaces (MFC, Swing, Windows Forms/WPF), relational database management systems (MySQL, SQL Server, PostgreSQL, Oracle), NoSQL solutions (MongoDB, Redis) and operating systems (Linux/Windows). Andriy has a great experience in development of distributed (multi-tier) software systems, multi-threaded applications, desktop applications, service-oriented architecture and rich Internet applications. Since 2006 he is actively working primarily with JEE / JSE platforms. As a professional he is always open to continuous learning and self-improvement to be more productive in the job he is really passioned about.
Advanced java 2 / 113
package com.javacodegeeks.advanced.construction;
public class NoArgConstructor { public NoArgConstructor() { // Constructor body here } }
This constructor will be called once new instance of the class is created using the new keyword. final NoArgConstructor noArgConstructor = new NoArgConstructor();
The constructors with arguments are the most interesting and useful way to parameterize new class instances creation. The following example defines a constructor with two arguments. package com.javacodegeeks.advanced.construction;
public class ConstructorWithArguments { public ConstructorWithArguments(final String arg1,final String arg2) { // Constructor body here } }
In this case, when class instance is being created using the new keyword, both constructor arguments should be provided. final ConstructorWithArguments constructorWithArguments = new ConstructorWithArguments( "arg1", "arg2" );
Interestingly, the constructors can call each other using the special this keyword. It is considered a good practice to chain constructors in such a way as it reduces code duplication and basically leads to having single initialization entry point. As an example, let us add another constructor with only one argument. public ConstructorWithArguments(final String arg1) { this(arg1, null); }
Java has yet another way to provide initialization logic using initialization blocks. This feature is rarely used but it is better to know it exists. package com.javacodegeeks.advanced.construction;
public class InitializationBlock { { // initialization code here } }
In a certain way, the initialization block might be treated as anonymous no-arg constructor. The particular class may have multiple initialization blocks and they all will be called in the order they are defined in the code. For example: package com.javacodegeeks.advanced.construction;
public class InitializationBlocks {
Advanced java 3 / 113
{ // initialization code here } { // initialization code here }
}
Initialization blocks do not replace the constructors and may be used along with them. But it is very important to mention that initialization blocks are always called before any constructor. package com.javacodegeeks.advanced.construction;
public class InitializationBlockAndConstructor { { // initialization code here } public InitializationBlockAndConstructor() { } }
Java provides certain initialization guarantees which developers may rely on. Uninitialized instance and class (static) variables are automatically initialized to their default values.
Table 1.1: datasheet Type Default Value boolean False byte 0 short 0 int 0 long 0L char u float 0.0f double 0.0d object reference null
Let us confirm that using following class as a simple example: package com.javacodegeeks.advanced.construction;
public class InitializationWithDefaults { private boolean booleanMember; private byte byteMember; private short shortMember; private int intMember; private long longMember; private char charMember; private float floatMember; private double doubleMember; private Object referenceMember;
Advanced java 5 / 113
So far we have talked about constructors and objects initialization but have not actually mentioned anything about their counter- part: objects destruction. That is because Java uses garbage collection to manage objects lifecycle and it is the responsibility of garbage collector to destroy unnecessary objects and reclaim the memory. However, there is one particular feature in Java called finalizers which resemble a bit the destructors but serves the different purpose of performing resources cleanup. Finalizers are considered to be a dangerous feature (which leads to numerous side- effects and performance issues). Generally, they are not necessary and should be avoided (except very rare cases mostly related to native objects). A much better alternative to finalizers is the introduced by Java 7 language construct called try-with-resources and AutoCloseable interface which allows to write clean code like this: try ( final InputStream in = Files.newInputStream( path ) ) { // code here }
So far we have looked through class instance construction and initialization. But Java also supports class-level initialization constructs called static initializers. There are very similar to the initialization blocks except for the additional static keyword. Please notice that static initialization is performed once per class-loader. For example: package com.javacodegeeks.advanced.construction;
public class StaticInitializationBlock { static { // static initialization code here } }
Similarly to initialization blocks, you may include any number of static initializer blocks in the class definition and they will be executed in the order in which they appear in the code. For example: package com.javacodegeeks.advanced.construction;
public class StaticInitializationBlocks { static { // static initialization code here } static { // static initialization code here } }
Because static initialization block can be triggered from multiple parallel threads (when the loading of the class happens in the first time), Java runtime guarantees that it will be executed only once and in thread-safe manner.
Over the years a couple of well-understood and widely applicable construction (or creation) patterns have emerged within Java community. We are going to cover the most famous of them: singleton, helpers, factory and dependency injection (also known as inversion of control).
Advanced java 6 / 113
Singleton is one of the oldest and controversial patterns in software developer’s community. Basically, the main idea of it is to ensure that only one single instance of the class could be created at any given time. Being so simple however, singleton raised a lot of the discussions about how to make it right and, in particular, thread-safe. Here is how a naive version of singleton class may look like: package com.javacodegeeks.advanced.construction.patterns;
public class NaiveSingleton { private static NaiveSingleton instance; private NaiveSingleton() { } public static NaiveSingleton getInstance() { if( instance == null ) { instance = new NaiveSingleton(); } return instance; } }
At least one problem with this code is that it may create many instances of the class if called concurrently by multiple threads. One of the ways to design singleton properly (but in non-lazy fashion) is using the static final property of the class. final property of the class. package com.javacodegeeks.advanced.construction.patterns;
public class EagerSingleton { private static final EagerSingleton instance = new EagerSingleton(); private EagerSingleton() { } public static EagerSingleton getInstance() { return instance; } }
If you do not want to waste your resources and would like your singletons to be lazily created when they are really needed, the explicit synchronization is required, potentially leading to lower concurrency in a multithreaded environments (more details about concurrency in Java will be discussing in part 9 of the tutorial, Concurrency best practices). package com.javacodegeeks.advanced.construction.patterns;
public class LazySingleton { private static LazySingleton instance; private LazySingleton() { } public static synchronized LazySingleton getInstance() { if( instance == null ) { instance = new LazySingleton(); } return instance; } }
Advanced java 8 / 113
public class Library implements BookFactory { @Override public Book newBook() { return new PaperBook(); } }
public class KindleLibrary implements BookFactory { @Override public Book newBook() { return new KindleBook(); } }
Now, the particular class of the Book is hidden behind BookFactory interface implementation, still providing the generic way to create books.
Dependency injection (also known as inversion of control) is considered as a good practice for class designers: if some class instance depends on the other class instances, those dependencies should be provided (injected) to it by means of constructors (or setters, strategies, etc.) but not created by the instance itself. Let us consider the following example: package com.javacodegeeks.advanced.construction.patterns;
import java.text.DateFormat; import java.util.Date;
public class Dependant { private final DateFormat format = DateFormat.getDateInstance(); public String format( final Date date ) { return format.format( date ); } }
The class Dependant needs an instance of DateFormat and it just creates one by calling DateFormat.getDateInstanc e() at construction time. The better design would be to use constructor argument to do the same thing: package com.javacodegeeks.advanced.construction.patterns;
import java.text.DateFormat; import java.util.Date;
public class Dependant { private final DateFormat format; public Dependant( final DateFormat format ) { this.format = format; } public String format( final Date date ) { return format.format( date ); } }
In this case the class has all its dependencies provided from outside and it would be very easy to change date format and write test cases for it.
Advanced java 9 / 113
In this part of the tutorial we have looked at classes and class instances construction and initialization techniques, along the way covering several widely used patterns. In the next part we are going to dissect the Object class and usage of its well-known methods: equals, hashCode, toString and clone.