blogger templates blogger widgets
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
This is part of a list of blog posts.
To browse the contents go to

Understanding JVM internals


What is the Java Virtual Machine?

The Java Virtual Machine, or JVM, is an abstract computer that runs compiled Java programs.

The JVM is "virtual" because it is generally implemented in software on top of a "real" hardware platform and operating system. All Java programs are compiled for the JVM. Therefore, the JVM must be implemented on a particular platform before compiled Java programs will run on that platform.


How it differs from C++?

C++ is compiled directly to machine code which is then executed directly by the central processing unit.

Java is compiled to byte-code which the Java virtual machine (JVM) then interprets at runtime. Actual Java implementations do just-in-time compilation to native machine code.
So you could say there are 2 levels of compilation in Java.
Alternatively, the GNU Compiler for Java can compile directly to machine code.


Is Java truly portable?

Portability isn't a black and white, yes or no kind of thing. Portability is how easily one can I take a program and run it on all of the platforms one cares about.

There are a few things that affect this. One is the language itself. The Java language spec generally leaves much less up to "the implementation". For example, "i = i++" is undefined in C and C++, but has a defined meaning in Java. More practically speaking, types like "int" have a specific size in Java (eg: int is always 32-bits), while in C and C++ the size varies depending on platform and compiler. These differences alone don't prevent you from writing portable code in C and C++, but you need to be a lot more diligent.

Another is the libraries. Java has a bunch of standard libraries that C and C++ don't have. For example, threading, networking and GUI libraries. Libraries of these sorts exist for C and C++, but they aren't part of the standard and the corresponding libraries available can vary widely from platform to platform.

Finally, there's the whole question of whether you can just take an executable and drop it on the other platform and have it work there. This generally works with Java, assuming there's a JVM for the target platform. (and there are JVMs for many/most platforms people care about) This is generally not true with C and C++. You're typically going to at least need a recompile, and that's assuming you've already taken care of the previous two points.


Java bytecodes

Java programs are compiled into a form called Java bytecodes. The JVM executes Java bytecodes, so Java bytecodes can be thought of as the machine language of the JVM. The Java compiler reads Java language source (.java) files, translates the source into Java bytecodes, and places the bytecodes into class (.class) files. The compiler generates one class file per class in the source.


JVM Instructions

To the JVM, a stream of bytecodes is a sequence of instructions. Each instruction consists of a one-byte opcode and zero or more operands. The opcode tells the JVM what action to take. If the JVM requires more information to perform the action than just the opcode, the required information immediately follows the opcode as operands.
A mnemonic is defined for each bytecode instruction. The mnemonics can be thought of as an assembly language for the JVM. For example, there is an instruction that will cause the JVM to push a zero onto the stack. The mnemonic for this instruction is iconst_0, and its bytecode value is 60 hex.


Word Size

The basic unit of size for data values in the Java virtual machine is the word--a fixed size chosen by the designer of each Java virtual machine implementation.

One word size must be large enough to hold a value of type byte (8 bits), short (16 bits), int (32 bits), char (16 bits), float (32 bits) , returnAddress (address of an opcode within the same method), or reference(ref to obj on heap).
Two words must be large enough to hold a value of type long or double (64 bits).

An implementation designer must therefore choose a word size that is at least 32 bits, but otherwise can pick whatever word size will yield the most efficient implementation.
The word size is often chosen to be the size of a native pointer on the host platform.
In practice, pointers will be of 16-bit on a 16-bit system (if you can find one), 32-bit on a 32-bit system, and 64bits on a 64-bit system.


Doesn’t this mean that there are no performance or memory gains when using types small that 64-bit?

In a 64-bit processor, the registers are all 64-bit so if your local variable is assigned to a register and is a boolean, byte, short, char, int, float, double or long it doesn't use memory and doesn't save any resources. Objects are 8-byte aligned so they always take up a multiple of 8-byte in memory. This means Boolean, Byte, Short, Character, Integer, Long , Float and Double, AtomicBoolean, AtomicInteger, AtomicLong, AtomicReference all use the same amount of memory.

Another interesting fact is that some integers are more performant on certain platforms.
For example, in a 32-bit computer (referenced by terms like 32-bit platform and Win32) the CPU is optimized to handle a 32-bit value at a time, and the 32 refers to the number of bits that the CPU can consume or produce in a single cycle. (This is a really simplistic explanation, but it gets the general idea across).

In a 64-bit computer (most recent AMD and Intel processors fall into this category), the CPU is optimized to handle 64-bit values at a time.

So, on a 32-bit platform, a 16-bit integer loaded into a 32-bit address would need to have 16 bits zeroed out so that the CPU could operate on it; a 32-bit integer would be immediately usable without any alteration, and a 64-bit integer would need to be operated on in two or more CPU cycles (once for the low 32-bits, and then again for the high 32-bits).
Conversely, on a 64-bit platform, 16-bit integers would need to have 48 bits zeroed, 32-bit integers would need to have 32 bits zeroed, and 64-bit integers could be operated on immediately.
Each platform and CPU has a 'native' bit-ness (like 32 or 64), and this usually limits some of the other resources that can be accessed by that CPU (for example, the 3GB/4GB memory limitation of 32-bit processors). The 80386 processor family (and later x86) processors made 32-bit the norm, but now companies like AMD and then Intel are currently making 64-bit the norm.

The method area, because it contains bytecodes, is aligned on byte boundaries.

The stack and garbage-collected heap are aligned on word (32-bit) boundaries.


So now when should we even be using short or byte types?

In most cases it wouldn’t be needed unless your use case requires for eg: you are working in image manipulation or reading/writing binary streams, etc.


JVM Architecture


The "virtual hardware" of the Java Virtual Machine can be divided into four basic parts:
the pc registers,
the JVM stack,
the garbage-collected heap,
the method area,
the runtime constant pool and
the native method stack

These parts are abstract, just like the machine they compose, but they must exist in some form in every JVM implementation.

Let's cover the components that are created for each thread first then then rest of the components.

Threads

A thread is a thread of execution in a program.

Why Threads?

They are light wait processes. Moores law states that execution speed increases with transisters increasing but now-a-days we create the overall speed by adding more cores. Adding threads enables the concept of executing/utilizing these cores parallel.

The JVM allows an application to have multiple threads of execution running concurrently.

In the Hotspot JVM there is a direct mapping between a Java Thread and a native operating system Thread. After preparing all of the state for a Java thread such as thread-local storage, allocation buffers, synchronization objects, stacks and the program counter, the native thread is created. The native thread is reclaimed once the Java thread terminates. The operating system is therefore responsible for scheduling all threads and dispatching them to any available CPU. Once the native thread has initialized it invokes the run() method in the Java thread. When the run() method returns, uncaught exceptions are handled, then the native thread confirms if the JVM needs to be terminated as a result of the thread terminating (i.e. is it the last non-deamon thread).

JVM System Threads

If you use jconsole or any debugger it is possible to see there are numerous threads running in the background. These background threads run in addition to the main thread, which is created as part of invoking public static void main(String[]), and any threads created by the main thread.

The main background system threads in the Hotspot JVM are:

> VM thread
This thread waits for operations to appear that require the JVM to reach a safe-point. The reason these operations have to happen on a separate thread is because they all require the JVM to be at a safe point where modifications to the heap can not occur. The type of operations performed by this thread are "stop-the-world" garbage collections, thread stack dumps, thread suspension and biased locking revocation.

> Periodic task thread
This thread is responsible for timer events (i.e. interrupts) that are used to schedule execution of periodic operations

> GC threads
These threads support the different types of garbage collection activities that occur in the JVM

> Compiler threads
These threads compile byte code to native code at runtime

> Signal dispatcher thread
This thread receives signals sent to the JVM process and handle them inside the JVM by calling the appropriate JVM methods.



PC Registers

> Each thread of a running program has its own pc register, or program counter, which is created when the thread is started.
> The pc register is one word in size, so it can hold both a native pointer and a returnAddress.
> As a thread executes a Java method, the pc register contains the address of the current instruction being executed by the thread. An "address" can be a native pointer (to the method area) or an offset from the beginning of a method's bytecodes. If a thread is executing a native method, the value of the pc register is undefined.


JVM stack

> Each Java Virtual Machine thread has a private Java Virtual Machine stack, created at the same time as the thread.
> A Java Virtual Machine stack stores frames.

Frame

> A new frame is created and added (pushed) to the top of stack for every method invocation.
> The frame is removed (popped) when the method returns normally or if an uncaught exception is thrown during the method invocation.

Each frame contains:
1. Local variable array
2. Return value
3. Operand stack
4. Reference to runtime constant pool for class of the current method

1. Local Variables Array

> The array of local variables contains all the variables used during the execution of the method, including a reference to this, all method parameters and other locally defined variables.
> For class methods (i.e. static methods) the method parameters start from zero, however, for instance method the zero slot is reserved for this.

A local variable can be:
• boolean
• byte
• char
• long
• short
• int
• float
• double
• reference
• returnAddress

> Each slot of local variable array is of 32-bits. So to store a character, short or byte variables one slot is used. Means all smaller data-types internally gets converted into int data type.
> Long and double take 2 slots.

2. Return value

This is the return value of the method.

3. Operand stack

Other than the program counter, which can't be directly accessed by instructions, the Java virtual machine has no registers. The Java virtual machine is stack-based rather than register-based because its instructions take their operands from the operand stack rather than from registers
> The Java virtual machine uses the operand stack as a work space.
> Most JVM byte code spends its time manipulating the operand stack by pushing, popping, duplicating, swapping, or executing operations that produce or consume values.

For example, a simple variable initialization results in two byte codes that interact with the operand stack.
int i;
Gets compiled to the following byte code:
0: iconst_0 // Push 0 to top of the operand stack
 1: istore_1 // Pop value from top of operand stack and store as local variable 1


4. References to runtime constant pool

Each frame contains a reference to the runtime constant pool. The reference points to the constant pool for the class of the method being executed for that frame. This reference helps to support dynamic linking.

C/C++ code is typically compiled to an object file then multiple object files are linked together to product a usable artifact such as an executable or dll. During the linking phase symbolic references in each object file are replaced with an actual memory address relative to the final executable.

In Java this linking phase is done dynamically at runtime.

When a Java class is compiled, all references to variables and methods are stored in the class's constant pool as a symbolic reference. A symbolic reference is a logical reference not a reference that actually points to a physical memory location. The JVM implementation can choose when to resolve symbolic references, this can happen when the class file is verified, after being loaded, called eager or static resolution, instead this can happen when the symbolic reference is used for the first time called lazy or late resolution.

However the JVM has to behave as if the resolution occurred when each reference is first used and throw any resolution errors at this point. Binding is the process of the field, method or class identified by the symbolic reference being replaced by a direct reference, this only happens once because the symbolic reference is completely replaced. If the symbolic reference refers to a class that has not yet been resolved then this class will be loaded. Each direct reference is stored as an offset against the storage structure associated with the runtime location of the variable or method.


Native Method Stack

When a thread invokes a native method, it enters a new world in which the structures and security restrictions of the Java virtual machine no longer hamper its freedom. A native method can likely access the runtime data areas of the virtual machine (it depends upon the native method interface), but can also do anything else it wants.


Let's now look a the aspects that are common/independent of Threads


Heap

> The Heap is used to allocate class instances and arrays at runtime.
> Arrays and objects can never be stored on the stack because a frame is not designed to change in size after it has been created. The frame only stores references that point to objects or arrays on the heap.
> Unlike primitive variables and references in the local variable array (in each frame) objects are always stored on the heap so they are not removed when a method ends. Instead objects are only removed by the garbage collector.

To support garbage collection the heap is divided into three sections:
1. Young Generation
Often split between Eden and Survivor
2. Old Generation (also called Tenured Generation)
3. Permanent Generation

JVM and JRE


What is the Java Virtual Machine?

The Java Virtual Machine, or JVM, is an abstract computer that runs compiled Java programs. The JVM is "virtual" because it is generally implemented in software on top of a "real" hardware platform and operating system. All Java programs are compiled for the JVM. Therefore, the JVM must be implemented on a particular platform before compiled Java programs will run on that platform.


How is Java execution different from C/C++?

In short, C is compiled directly to machine code which is then executed directly by the central processing unit.

Normally the C’s program building process involves four stages and utilizes different ‘tools’ such as a preprocessor, compiler, assembler, and linker.

1. Preprocessing is the first pass of any C compilation. It processes include-files, conditional compilation instructions and macros.
2. Compilation is the second pass. It takes the output of the preprocessor, and the source code, and generates assembler source code.
3. Assembly is the third stage of compilation. It takes the assembly source code and produces an assembly listing with offsets. The assembler output is stored in an object file.
4. Linking is the final stage of compilation. It takes one or more object files or libraries as input and combines them to produce a single (usually executable) file. In doing so, it resolves references to external symbols, assigns final addresses to procedures/functions and variables, and revises code and data to reflect new addresses (a process called relocation).



Java is compiled to byte-code which the Java virtual machine (JVM) then interprets at runtime. Actual Java implementations do just-in-time compilation to native machine code. Alternatively, the GNU Compiler for Java can compile directly to machine code.



So now what is the difference between interpreter and JIT compiler?

Answer given below from stackoverflow.

With JVM, both interpreter and compiler (the JVM compiler and not the source-code compiler like javac) produce native code (aka Machine language code for the underlying physical CPU like x86) from byte code.

What's the difference then:
The difference is in how they generate the native code, how optimized it is as well how costly the optimization is. Informally, an interpreter pretty much converts each byte-code instruction to corresponding native instruction by looking up a predefined JVM-instruction to machine instruction mapping (see below pic). Interestingly, a further speedup in execution can be achieved, if we take a section of byte-code and convert it into machine code - because considering a whole logical section often provides rooms for optimization as opposed to converting (interpreting) each line in isolation (to machine instruction). This very act of converting a section of byte-code into (presumably optimized) machine instruction is called compiling (in the current context). When the compilation is done at run-time, the compiler is called JIT compiler.


What makes Java portable?

Portability isn't a black and white, yes or no kind of thing. Portability is how easily one can I take a program and run it on all of the platforms one cares about.
There are a few things that affect this. One is the language itself. The Java language spec generally leaves much less up to "the implementation". For example, "i = i++" is undefined in C and C++, but has a defined meaning in Java. More practically speaking, types like "int" have a specific size in Java (eg: int is always 32-bits), while in C and C++ the size varies depending on platform and compiler. These differences alone don't prevent you from writing portable code in C and C++, but you need to be a lot more diligent.

Another is the libraries. Java has a bunch of standard libraries that C and C++ don't have. For example, threading, networking and GUI libraries. Libraries of these sorts exist for C and C++, but they aren't part of the standard and the corresponding libraries available can vary widely from platform to platform.
Finally, there's the whole question of whether you can just take an executable and drop it on the other platform and have it work there. This generally works with Java, assuming there's a JVM for the target platform. (and there are JVMs for many/most platforms people care about) This is generally not true with C and C++. You're typically going to at least need a recompile, and that's assuming you've already taken care of the previous two points.



Java bytecodes

Java programs are compiled into a form called Java bytecodes. The JVM executes Java bytecodes, so Java bytecodes can be thought of as the machine language of the JVM. The Java compiler reads Java language source (.java) files, translates the source into Java bytecodes, and places the bytecodes into class (.class) files. The compiler generates one class file per class in the source.

To the JVM, a stream of bytecodes is a sequence of instructions. Each instruction consists of a one-byte opcode and zero or more operands. The opcode tells the JVM what action to take. If the JVM requires more information to perform the action than just the opcode, the required information immediately follows the opcode as operands.
A mnemonic is defined for each bytecode instruction. The mnemonics can be thought of as an assembly language for the JVM. For example, there is an instruction that will cause the JVM to push a zero onto the stack. The mnemonic for this instruction is iconst_0, and its bytecode value is 60 hex.


Java Language Specification

Not all major programming languages have specifications, and languages can exist and be popular for decades without a specification. ALGOL 68 was the first (and possibly one of the last) major language for which a full formal definition was made before it was implemented.

When Sun was the steward of Java, they would write specifications for features like Java EE and JPA, giving other vendors the freedom to implement as they wished. Sun would usually have an implementation of their own with which to compete, but their goal was to sell hardware. Encouraging other vendors to provide competing implementations only furthered that aim.

In Java-land these specifications are started as Java Specification Requests (JSRs). Defined here: https://jcp.org/en/jsr/overview. Once accepted, these are specifications.

Sun made most of the JDK source code (not the JVM) freely available under open-source license.


Java Virtual Machine Specification

On November 13, 2006, Sun released much of its Java virtual machine (JVM) as free and open-source software, (FOSS), under the terms of the GNU General Public License (GPL). On May 8, 2007, Sun finished the process, making all of its JVM's core code available under free software/open-source distribution terms, aside from a small portion of code to which Sun did not hold the copyright.

https://docs.oracle.com/javase/specs/

JVM specification dictates how a JVM needs to respond to byte code commands.

Other famous JVM implementation are OpenJDK, IBM J9, GCJ, etc.

The OpenJDK is the open-source implementation of the Java SE 7 JSR (JSR 336). Now there is almost no difference between the Oracle JDK and the OpenJDK. Last year, Oracle took this decision : Moving to OpenJDK as the official Java SE 7 Reference Implementation


Word Size

The basic unit of size for data values in the Java virtual machine is the word--a fixed size chosen by the designer of each Java virtual machine implementation.
One word size must be large enough to hold a value of type byte (8 bits), short (16 bits), int (32 bits), char (16 bits), float (32 bits) , returnAddress (address of an opcode within the same method), or reference(ref to obj on heap).

Two words must be large enough to hold a value of type long or double (64 bits).

On a 64-bit machine one word will be able to hold all types.

An implementation designer must therefore choose a word size that is at least 32 bits, but otherwise can pick whatever word size will yield the most efficient implementation.
The word size is often chosen to be the size of a native pointer on the host platform.
In practice, pointers will be of 16-bit on a 16-bit system (if you can find one), 32-bit on a 32-bit system, and 64bits on a 64-bit system.

Doesn’t this mean that there are no performance or memory gains when using types small that 64-bit?

In a 64-bit processor, the registers are all 64-bit so if your local variable is assigned to a register and is a boolean, byte, short, char, int, float, double or long it doesn't use memory and doesn't save any resources. Objects are 8-byte aligned so they always take up a multiple of 8-byte in memory. This means Boolean, Byte, Short, Character, Integer, Long , Float and Double, AtomicBoolean, AtomicInteger, AtomicLong, AtomicReference all use the same amount of memory.
Another interesting fact is that some integers are more performant on certain platforms.

For example, in a 32-bit computer (referenced by terms like 32-bit platform and Win32) the CPU is optimized to handle a 32-bit value at a time, and the 32 refers to the number of bits that the CPU can consume or produce in a single cycle. (This is a really simplistic explanation, but it gets the general idea across).
In a 64-bit computer (most recent AMD and Intel processors fall into this category), the CPU is optimized to handle 64-bit values at a time.
So, on a 32-bit platform, a 16-bit integer loaded into a 32-bit address would need to have 16 bits zeroed out so that the CPU could operate on it; a 32-bit integer would be immediately usable without any alteration, and a 64-bit integer would need to be operated on in two or more CPU cycles (once for the low 32-bits, and then again for the high 32-bits).

Conversely, on a 64-bit platform, 16-bit integers would need to have 48 bits zeroed, 32-bit integers would need to have 32 bits zeroed, and 64-bit integers could be operated on immediately.
Each platform and CPU has a 'native' bit-ness (like 32 or 64), and this usually limits some of the other resources that can be accessed by that CPU (for example, the 3GB/4GB memory limitation of 32-bit processors). The 80386 processor family (and later x86) processors made 32-bit the norm, but now companies like AMD and then Intel are currently making 64-bit the norm.

So now when should we even be using short or byte types?

In most cases it wouldn’t be needed unless your use case requires for eg: you are working in image manipulation or reading/writing binary streams, etc.
The method area, because it contains bytecodes, is aligned on byte boundaries. The stack and garbage-collected heap are aligned on word (32-bit) boundaries.



JVM Architecture

The "virtual hardware" of the Java Virtual Machine can be divided into 6 basic parts:
The pc registers,
the Java stack,
the garbage-collected heap,
the method area,
the runtime constant pool
and the native method stack

These parts are abstract, just like the machine they compose, but they must exist in some form in every JVM implementation.


PC Registers

Each thread of a running program has its own pc register, or program counter, which is created when the thread is started.
The pc register is one word in size, so it can hold both a native pointer and a returnAddress.

As a thread executes a Java method, the pc register contains the address of the current instruction being executed by the thread. An "address" can be a native pointer (to the method area) or an offset from the beginning of a method's bytecodes. If a thread is executing a native method, the value of the pc register is undefined.


Java stack

Each Java Virtual Machine thread has a private Java Virtual Machine stack, created at the same time as the thread.
A Java Virtual Machine stack stores frames.

Frame

A frame is used to store data and partial results, as well as to perform dynamic linking, return values for methods, and dispatch exceptions.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes, whether that completion is normal or abrupt (it throws an uncaught exception).
Each frame contains:
• Local variable array
• Operand stack
• Frame data

Local Variables Array

The array of local variables contains all the variables used during the execution of the method, including a reference to this, all method parameters and other locally defined variables. For class methods (i.e. static methods) the method parameters start from zero, however, for instance method the zero slot is reserved for this.
A local variable can be:
• boolean
• byte
• char
• long
• short
• int
• float
• double
• reference
• returnAddress

Each slot of local variable array is of 32-bits. So to store a character, short or byte variables one slot is used. Means all smaller data-types internally gets converted into int data type.
Long and double take 2 slots.

Operand Stack

Like the local variables, the operand stack is organized as an array of words. But unlike the local variables, which are accessed via array indices, the operand stack is accessed by pushing and popping values.
The virtual machine stores the same data types in the operand stack that it stores in the local variables, Other than the program counter, which can't be directly accessed by instructions, the Java virtual machine has no registers. The Java virtual machine is stack-based rather than register-based because its instructions take their operands from the operand stack rather than from registers.
The Java virtual machine uses the operand stack as a work space. Many instructions pop values from the operand stack, operate on them, and push the result. For example, the iadd instruction adds two integers by popping two ints off the top of the operand stack, adding them, and pushing the int result.

Here is how a Java virtual machine would add two local variables that contain ints and store the intresult in a third local variable:
iload_0 // push the int in local variable 0
iload_1 // push the int in local variable 1
iadd // pop two ints, add them, push result
istore_2 // pop int, store into local variable


Frame Data

This is to support constant pool resolution, normal method return, and exception dispatch.

Many instructions in the Java virtual machine's instruction set refer to entries in the constant pool. Some instructions merely push constant values of type int, long, float, double, or String from the constant pool onto the operand stack. Some instructions use constant pool entries to refer to classes or arrays to instantiate, fields to access, or methods to invoke. Other instructions determine whether a particular object is a descendant of a particular class or interface specified by a constant pool entry.

Aside from constant pool resolution, the frame data must assist the virtual machine in processing a normal or abrupt method completion. If a method completes normally (by returning), the virtual machine must restore the stack frame of the invoking method. It must set the pc register to point to the instruction in the invoking method that follows the instruction that invoked the completing method. If the completing method returns a value, the virtual machine must push that value onto the operand stack of the invoking method.

The frame data must also contain some kind of reference to the method's exception table, which the virtual machine uses to process any exceptions thrown during the course of execution of the method.
An exception table defines ranges within the bytecodes of a method that are protected by catch clauses. Each entry in an exception table gives a starting and ending position of the range protected by a catch clause, an index into the constant pool that gives the exception class being caught, and a starting position of the catch clause's code.

Native Method Stacks
In addition to all the runtime data areas defined by the Java virtual machine specification and described previously, a running Java application may use other data areas created by or for native methods. When a thread invokes a native method, it enters a new world in which the structures and security restrictions of the Java virtual machine no longer hamper its freedom. A native method can likely access the runtime data areas of the virtual machine (it depends upon the native method interface), but can also do anything else it wants. It may use registers inside the native processor, allocate memory on any number of native heaps, or use any kind of stack.


The Heap

Whenever a class instance or array is created in a running Java application, the memory for the new object is allocated from a single heap. As there is only one heap inside a Java virtual machine instance, all threads share it. Because a Java application runs inside its "own" exclusive Java virtual machine instance, there is a separate heap for every individual running application. There is no way two different Java applications could trample on each other's heap data. 

Garbage Collection

A garbage collector's primary function is to automatically reclaim the memory used by objects that are no longer referenced by the running application. It may also move objects as the application runs to reduce heap fragmentation.

A garbage collector is not strictly required by the Java virtual machine specification. The specification only requires that an implementation manage its own heap in some manner. For example, an implementation could simply have a fixed amount of heap space available and throw an OutOfMemory exception when that space fills up. While this implementation may not win many prizes, it does qualify as a Java virtual machine. 


Object Representation

The Java virtual machine specification is silent on how objects should be represented on the heap. 







Floating point arithmetic and doubles in Java


Here comes a newbie java programmer

Imagine you want to split $200 between four people. First, two of them will get 1/3 and the other two will get 1/6.


double a = 200;
double b = a / 3d;
double c = b / 2d;
double d = b + b + c + c;
System.out.println(a); // 200.0
System.out.println(b); // 66.66666666666667
System.out.println(c); // 33.333333333333336
System.out.println(d); // 200.00000000000003

That’s strange. Anyways then you try something like this


float x = 1.0f;
int p = 0;
while (x != x + 1) {
 // this should go for ever but
 // it does exit within few loops
 x = x * 3;
 p++;
}
System.out.println(p);
System.out.println(x);

So you check the internet and find that you should be using BigDecimal in java for handling floating point numbers safely.

So you now try the same example using BigDecimal to see if it works as expected.


BigDecimal a = new BigDecimal(200.0);
BigDecimal b = a.divide(new BigDecimal(3.0));
BigDecimal c = b.divide(new BigDecimal(2.0));
BigDecimal d = b.add(b).add(c).add(c);
System.out.println(b);
System.out.println(c);
System.out.println(d);

But his throws
java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.


This is because you're not specifying a precision and a rounding-mode. BigDecimal is complaining that it could use 10, 20, 5000, or infinity decimal places, and it still wouldn't be able to give you an exact representation of the number. So instead of giving you an incorrect BigDecimal, it just whinges at you.


BigDecimal a = new BigDecimal(200.0);
BigDecimal b = a.divide(new BigDecimal(3.0), 2, RoundingMode.FLOOR); 
BigDecimal c = b.divide(new BigDecimal(2.0), 2, RoundingMode.FLOOR);
BigDecimal d = b.add(b).add(c).add(c).setScale(0, RoundingMode.UP);
System.out.println(b);
System.out.println(c);
System.out.println(d);

First we specify decimal precision as 2 and rouding to floor for divisions
Then after the addition we get 199.98 so we round it off to 0 decimals and round it up to the nearest integer.
So far so good.
Now that we have used BigDecimal this far we try few more scenarios to make sure it is working how we expect it to.



BigDecimal a = new BigDecimal(0.2d);
BigDecimal b = new BigDecimal(String.valueOf(0.2d));
BigDecimal c = new BigDecimal("0.2");
BigDecimal d = new BigDecimal("0.20");
System.out.println(a);   // 0.200000000000000011102230246251565404236316680908203125
System.out.println(b);       // 0.2
System.out.println(c);       // 0.2
System.out.println(d);       // 0.20
System.out.println(a.equals(b));  // false
System.out.println(a.equals(c));  // false
System.out.println(a.equals(d));  // false
System.out.println(b.equals(c));  // true
System.out.println(b.equals(d));  // false
System.out.println(c.equals(d));  // false
System.out.println(a.compareTo(b)); // 1
System.out.println(a.compareTo(c)); // 1
System.out.println(a.compareTo(d)); // 1
System.out.println(b.compareTo(c)); // 0
System.out.println(b.compareTo(d)); // 0
System.out.println(c.compareTo(d)); // 0

As you can see, our expectation was wrong. If you read the Javadoc, then you can see the reasons behind it. Or, here is my three-point extract from said Javadoc.
1. The doubleconstructor can be somewhat unpredictable. This has something to do with the binary representation of floating point numbers. String constructors are predictable. So if you want to get an exact number from double, then try taking the path of double -> String -> BigDecimal.
2. Theequalsmethod doesn't work the same way as natural ordering. This is because BigDecimal is composed of two components calledunscalledValueandscale. Thevalue represented by the number is(unscaledValue × 10-scale). Since both components are part of the equals,thentrueis returned only if numbers have the same scale (that means0.2and0.20are not equal). TheHashCodemethod follows the contract as well (therefore you can expect different hash codes for0.2and0.20).
3. TheCompareTomethod works in the same way as natural ordering. Numberais just greater than others due to a differentconstructor.

Rule :
If you are dealing with inputs and you are planning to put it into BigDecimal then always don’t cast the incoming data to double instead use it as String.
Eg: new BigDecimal("0.2");

Let’s see why all this fuss about double and BigDecimals.

Concept of floating point numbers and double/float variables

It's really easy to write integers as binary numbers in 2's complement form. It's a lot more difficult to express floating point numbers in a form that a computer can understand. The biggest problem, of course, is keeping track of the decimal point.
There are lots of possible ways to write floating point numbers as strings of binary digits. Here are some things that the original designers might have had to consider when picking a solution.
• Range
To be useful, your method should allow very large positive and negative numbers.
• Precision
Can you tell the difference between 1.7 and 1.8? How about between 1.700001 and 1.700002? How many decimal places should you remember?
• Time Efficiency
Does your solution make comparisons and arithmetic operations fast and easy? 
• Space Considerations
An extremely precise representation of the square root of 3 is generally a wonderful thing, unless you require a megabyte to store it. 
• 1-1 Relationships
Your solution will be a lot simpler if each floating-point number can be written only one way, and vice versa.


How IEEE people solved it

The method that the original developers finally hit upon uses the idea of scientific notation. Scientific notation is a standard way to express numbers; it makes them easy to read and compare. You're probably familiar with scientific notation with base-10 numbers. You just factor your number into two parts: a value in the range of [1 <= n < 10], and a power of 10. For eg:


The same idea applies here, except that you need to use powers of 2 because the computer deals with binary numbers.
Just factor your number into a value in the range [1 <= n < 2], and a power of 2. * For eg:


You're almost done when the number is in this form:

This was a clever move. Instead of one messy value, you now have three important pieces of information that can identify the number.

If the sign bit is a 0, then the number is positive; (-1)^0 = 1. If the sign bit is a 1, the number is negative.

We always factor so that the number in parentheses equals 1 + some fraction. Since we know that the 1 is there, the only important thing is the fraction, which you will write as a binary string.

The power of 2 that you got in the last step is simply an integer. Since you don't want to deal with any messy negative numbers, you can add a constant value (the bias) to that power. 

For single-precision floating-point, the bias=127.
For double-precision, the bias=1023.

The sum of the bias and the power of 2 is the exponent that actually goes into the IEEE 754 string. Remember, the exponent = power + bias. (Alternatively, the power = exponent-bias).
When you have calculated these binary values, you can put them into a 32- or 64-bit field.

The digits are arranged like this:


Check out these examples to get a clear idea -

Example: Converting double to IEEE 754 Form

Example: Converting IEEE 754 to Float


Q. What rule does Java use to print out a double?
A. By setting all the exponent bits to 1. Here's the java.lang.Double API. It always prints at least one digit after the decimal. After that, it uses as many digits as necessary (but no more) to distinguish the number from the nearest representable double.

Q. How are zero, infinity and NaN represented using IEEE 754?
A. By setting all the exponent bits to 1. Positive infinity = 0x7ff0000000000000 (all exponent bits 1, sign bit 0 and all mantissa bits 0), negative infinity = 0xfff0000000000000 (all exponent bits 1, sign bit 1 and all mantissa bits 0), NaN = 0x7ff8000000000000 (all exponent bits 1, at least one mantissa bit set). Positive zero = all bits 0. Negative zero = all bits 0, except sign bit which is 1.

Q. What is StrictMath?
A. Java's Math library guarantees its results to be with 1 or to 2 ulps of the true answer. Java's StrictMath guarantees that all results are accurate to within 1/2 ulp of the true answer. A classic tradeoff of speed vs. accuracy.


Q. What are ulps


// π with 20 decimal digits
BigDecimal π = new BigDecimal("3.14159265358979323846");

// truncate to a double floating point
double p0 = π.doubleValue();
// -> 3.141592653589793  (hex: 0x1.921fb54442d18p1)

// p0 is smaller than π, so find next number representable as double
double p1 = Math.nextUp(p0);
// -> 3.1415926535897936 (hex: 0x1.921fb54442d19p1)

//if you are wondering which number is taken as the next number
//what java does is take 
Double.longBitsToDouble(Double.doubleToRawLongBits(number)+1)
//that means incrementing the current binary representation of the number


// ulp(Ï€) is the difference between p1 and p0
BigDecimal ulp = new BigDecimal(p1).subtract(new BigDecimal(p0));
// -> 4.44089209850062616169452667236328125E-16
// (this is precisely 2**(-51))

// same result when using the standard library function
double ulpMath = Math.ulp(p0);
// -> 4.440892098500626E-16 (hex: 0x1.0p-51)

Q. What is strictfp modifier?
A. It is also possible to use the strictfp modifier when declaring a class or method. This ensures that the floating point results will be bit-by-bit accurate across different JVMs. The IEEE standard allows processors to perform intermediate computations using more precision if the result would overflow. The strictfp requires that every intermediate result be truncated to 64-bit double format. This can be a major performance hit since Intel Pentium processor registers operate using IEEE 754's 80-bit double-extended format. Not many people have a use for this mode.

Q. What does the compiler flag javac -ffast-math do?
A. It relaxes some of the rounding requirements of IEEE. It makes some floating point computations faster.

Q. Are integers always represented exactly using IEEE floating point?
A. Yes, barring overflow of the 52 bit mantissa. The smallest positive integer that is not represented exactly using type double is 2^53 + 1 = 9,007,199,254,740,993.

Q. Does (a + b) always equal (b + a) when a and b are floating point numbers?
A. Yes.

Q. Does x / y always equal the same value, independent of my platform?
A. Yes. IEEE requires that operations (+ * - /) are performed exactly and then rounded to the nearest floating point number (using Banker's round if there is a tie: round to nearest even number). This improves portability at the expense of efficiency.



Links infered:
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
http://introcs.cs.princeton.edu/java/91float/
https://dzone.com/articles/why
https://dzone.com/articles/arbitrary-precision-numbers?edition=292907&utm_source=Daily%20Digest&utm_medium=email&utm_campaign=dd%202017-04-21

Java Email Code

The following is a sample code to send email from java program using gmail smtp server.

final String username = "your-email-id";
final String password = "your-password";

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
        "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
    new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username,password);
        }
    });
try {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("your-email-id"));
    message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("your-email-id"));
    message.setSubject("Testing Subject");
    message.setText("Dear Mail Crawler,"
            + "\n\n No spam to my email, please!");

    Transport.send(message);

    System.out.println("Done");

} catch (MessagingException e) {
    throw new RuntimeException(e);
}

Behavioural Design Patterns



Template Method pattern

It defines the steps to execute an algorithm in the base class and it can provide default implementation that might be common for all or some of the subclasses.

Client:

Tea tea = new Tea();
tea.prepareRecipe();
Coffee coffee = new Coffee();
coffee.prepareRecipe();



// We find that the algorithm to make coffee and tea are similar and they are
// not supposed to be controlled within the Tea or Coffee classes instead 
// the algorithm should be moved out

abstract class Beverage {
final public void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}

abstract public void brew();

abstract public void addCondiments();

//some of the methods could be final - making that step in the algorithm compulsory
public final void boilWater() {
println("Boil water");
}

public void pourInCup() {
println("Pour in Cup");
}
}

class Coffee extends Beverage {
public void brew() {
println("Brew Coffee");
}

public void addCondiments() {
println("Add Sugar and Milk");
}
}

class Tea extends Beverage {
public void brew() {
println("Steep Tea");
}

public void addCondiments() {
println("Add Lemon");
}
}

JDK:
All non-abstract methods of InputStream, OutputStream, Reader, Writer
All non-abstract methods of AbstractList, AbstractSet and AbstractMap



Mediator pattern

Mediator design pattern is used to provide a centralized communication medium between different objects in a system.

Client:

ChatMediator mediator = new ChatMediator();
User user1 = new Personal(mediator, "John");
User user2 = new Personal(mediator, "Kamal");
User user3 = new Manager(mediator, "Geo");

user2.send("hello people");
user3.send("hello boys");


/*
* 
* Mediator design pattern is used to provide a centralized communication medium
* between different objects in a system.
*/
abstract class User {
protected ChatMediator mediator;
protected String name;

public User(ChatMediator med, String name) {
this.mediator = med;
this.name = name;
this.mediator.addUser(this);
}

public abstract void send(String msg);

public abstract void receive(String msg);
}

class Personal extends User {

public Personal(ChatMediator med, String name) {
super(med, name);
}

@Override
public void send(String msg) {
println(this.name+": Sending Message="+msg); 
mediator.sendMessage(msg, this);
}

@Override
public void receive(String msg) {
println(this.name+": Received Message:"+msg);
}

}


class Manager extends User {

public Manager(ChatMediator med, String name) {
super(med, name);
}

@Override
public void send(String msg) {
println(this.name+": Sending Sacred Message="+msg); 
mediator.sendMessage(msg, this);
}

@Override
public void receive(String msg) {
println(this.name+": Received Message:"+msg);
}

}

//Mediator class helps to provide a mechanism for different user objects to
//communicate

class ChatMediator  {
private List users;

public ChatMediator() {
this.users = new ArrayList<>();
}

public void addUser(User user) {
this.users.add(user);
}

public void sendMessage(String msg, User user) {
for (User u : this.users) {
// message should not be received by the user sending it
if (u != user) {
u.receive(msg);
}
}
}
}

Output:
[main] Kamal: Sending Message=hello people
[main] John: Received Message:hello people
[main] Geo: Received Message:hello people
[main] Geo: Sending Sacred Message=hello boys
[main] John: Received Message:hello boys
[main] Kamal: Received Message:hello boys

JDK:
java.util.Timer class scheduleXXX() methods
Java Concurrency Executor execute() method
java.lang.reflect.Method invoke() method
JMS



Chain of responsibility pattern

It is used to achieve lose coupling in software design where a request from client is passed to a chain of objects to process them. Then the object in the chain will decide themselves who will be processing the request and whether the request is required to be sent to the next object in the chain or not.

Client:

DispenseChain chain5 = new Dollar50Dispenser();
DispenseChain chain2 = new Dollar20Dispenser();
DispenseChain chain1 = new Dollar10Dispenser();
chain5.setNextChain(chain2);
chain2.setNextChain(chain1);

chain5.dispense(new Currency(187));



/**
* Gives more than one object an opportunity to handle a request by linking
* receiving objects together.
*/

// this is the object that is handled
class Currency {
private int amount;

public Currency(int amt) {
amount = amt;
}

public int getAmount() {
return amount;
}
}

// this is the interface for all request handlers
interface DispenseChain {
void setNextChain(DispenseChain nextChain);

void dispense(Currency cur);
}

class Dollar50Dispenser implements DispenseChain {
private DispenseChain chain;

@Override
public void setNextChain(DispenseChain nextChain) {
chain = nextChain;
}

@Override
public void dispense(Currency cur) {
if (cur.getAmount() >= 50) {
int num = cur.getAmount() / 50;
int remainder = cur.getAmount() % 50;
println("Dispensing " + num + " 50$ note");
if (remainder != 0)
chain.dispense(new Currency(remainder));
} else {
chain.dispense(cur);
}
}
}

class Dollar20Dispenser implements DispenseChain {
private DispenseChain chain;

@Override
public void setNextChain(DispenseChain nextChain) {
chain = nextChain;
}

@Override
public void dispense(Currency cur) {
if (cur.getAmount() >= 20) {
int num = cur.getAmount() / 20;
int remainder = cur.getAmount() % 20;
println("Dispensing " + num + " 20$ note");
if (remainder != 0)
chain.dispense(new Currency(remainder));
} else {
chain.dispense(cur);
}
}
}

class Dollar10Dispenser implements DispenseChain {
 private DispenseChain chain;

 @Override
 public void setNextChain(DispenseChain nextChain) {
  chain = nextChain;
 }

 @Override
 public void dispense(Currency cur) {
  int num = cur.getAmount() / 10;
  int remainder = cur.getAmount() % 10;
  println("Dispensing " + num + " 10$ note");
  if (remainder != 0) {
   if (chain != null && remainder > 10) {
    chain.dispense(new Currency(remainder));
   } else {
    println("Unable to dispence " + remainder + " ,amound should be in the multiples of 10");
   }
  }

 }
}

Output:
[main] Dispensing 3 50$ note
[main] Dispensing 1 20$ note
[main] Dispensing 1 10$ note
[main] Unable to dispence 7 ,amound should be in the multiples of 10

JDK:
java.util.logging.Logger#log()
javax.servlet.Filter#doFilter()



Observer Pattern

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

A very common example is Publish/Subscriber on Topics.

Client:

MyTopic topic = new MyTopic();

// create observers
Observer obj1 = new MyTopicSubscriber("observer-1");
Observer obj2 = new MyTopicSubscriber("observer-2");
Observer obj3 = new MyTopicSubscriber("observer-3");

// register observers to the subject
topic.register(obj1);
topic.register(obj2);
topic.register(obj3);

// attach observer to subject
obj1.setSubject(topic);
obj2.setSubject(topic);
obj3.setSubject(topic);

// check if any update is available
obj1.update();

// now send message to subject
topic.postMessage("New Message");



interface Subject {
// methods to register and unregister observers
public void register(Observer obj);

public void unregister(Observer obj);

// method to notify observers of change
public void notifyObservers();

// method to get updates from subject
public Object getUpdate(Observer obj);
}

interface Observer {
// method to update the observer, used by subject
public void update();

// attach with subject to observe
public void setSubject(Subject sub);
}

class MyTopic implements Subject {

private List<observer> observers;
private String message;
private boolean changed;
private final Object MUTEX = new Object();

public MyTopic() {
observers = new ArrayList<>();
}

@Override
public void register(Observer obj) {
if (obj == null)
throw new NullPointerException("Null Observer");
synchronized (MUTEX) {
if (!observers.contains(obj))
observers.add(obj);
}
}

@Override
public void unregister(Observer obj) {
synchronized (MUTEX) {
observers.remove(obj);
}
}

@Override
public void notifyObservers() {
List observersLocal = null;
// synchronization is used to make sure any observer registered
// after message is received is not notified
synchronized (MUTEX) {
if (!changed)
return;
observersLocal = new ArrayList<>(observers);
changed = false;
}
for (Observer obj : observersLocal) {
obj.update();
}
}

@Override
public Object getUpdate(Observer obj) {
return message;
}

// method to post message to the topic
public void postMessage(String msg) {
println("Message Posted to Topic:" + msg);
message = msg;
changed = true;
notifyObservers();
}
}

class MyTopicSubscriber implements Observer {

private String name;
private Subject topic;

public MyTopicSubscriber(String nm) {
name = nm;
}

@Override
public void update() {
String msg = (String) topic.getUpdate(this);
if (msg == null) {
println(name + ":: No new message");
} else
println(name + ":: Consuming message::" + msg);
}

@Override
public void setSubject(Subject sub) {
topic = sub;
}
}

Output:
[main] observer-1:: No new message
[main] Message Posted to Topic:New Message
[main] observer-1:: Consuming message::New Message
[main] observer-2:: Consuming message::New Message
[main] observer-3:: Consuming message::New Message



Strategy pattern

It is used when we have multiple algorithm for a specific task and client decides the actual implementation to be used at runtime.

Strategy pattern is also known as Policy Pattern.

Client:

Customer a = new Customer(new NormalStrategy());

// Normal billing
a.add(1.0, 1);

// Start Happy Hour
a.setStrategy(new HappyHourStrategy());
a.add(1.0, 2);

a.printBill();


class Customer {

private List drinks;

//if strategy pattern was not used then
//we would have getPrice method in Customer class and 
//will have a huge if else statement for different customer strategy 
//scenarios. the pattern helps to take that logic out and
//make it extensible and modifiable without touching the customer class

private BillingStrategy strategy;

public Customer(BillingStrategy strategy) {
drinks = new ArrayList();
this.strategy = strategy;
}

public void add(double price, int quantity) {
drinks.add(strategy.getFinalPrice(price * quantity));
}

// Payment of bill
public void printBill() {
double sum = 0;
for (Double i : drinks) {
sum += i;
}
System.out.println("Total due: " + sum);
drinks.clear();
}

// Set Strategy
public void setStrategy(BillingStrategy strategy) {
this.strategy = strategy;
}

}


interface BillingStrategy {
public double getFinalPrice(double rawPrice);
}

// Normal billing strategy (unchanged price)
class NormalStrategy implements BillingStrategy {

@Override
public double getFinalPrice(double rawPrice) {
return rawPrice;
}

}

// Strategy for Happy hour (50% discount)
class HappyHourStrategy implements BillingStrategy {

@Override
public double getFinalPrice(double rawPrice) {
return rawPrice * 0.5;
}

}

JDK:
Collections.sort()
Arrays.sort()



Command pattern

It’s used to implement lose coupling in a request-response model. In command pattern, the request is send to the invoker and invoker pass it to the encapsulated command object. Command object passes the request to the appropriate method of Receiver to perform the specific action.

Client:

Computer computer = new Computer();
Command shutdown = new ShutDownCommand(computer);
Command restart = new RestartCommand(computer);

Switch s = new Switch();

String str = "shutdown"; // get value based on real situation

if (str == "shutdown") {
s.storeAndExecute(shutdown);
} else {
s.storeAndExecute(restart);
}


/* The Command interface */
interface Command {
void execute();
}

// in this example, suppose you use a switch to control computer

/* The Invoker class */
class Switch {
private List history = new ArrayList();

public Switch() {
}

public void storeAndExecute(Command command) {
history.add(command); // optional, can do the execute only!
command.execute();
}
}

/* The Receiver class */
class Computer {

public void shutDown() {
println("computer is shut down");
}

public void restart() {
println("computer is restarted");
}
}

/* The Command for shutting down the computer */
class ShutDownCommand implements Command {
private Computer computer;

public ShutDownCommand(Computer computer) {
this.computer = computer;
}

public void execute() {
computer.shutDown();
}
}

/* The Command for restarting the computer */
class RestartCommand implements Command {
private Computer computer;

public RestartCommand(Computer computer) {
this.computer = computer;
}

public void execute() {
computer.restart();
}
}

JDK:
Runnable
swing.Action



State pattern

If we have to change the behavior of an object based on its state, we can have a state variable in the Object and use if-else condition block to perform different actions based on the state. State pattern is used to provide a systematic and lose-coupled way to achieve this through Context and State implementations.
Context is the class that has a State reference to one of the concrete implementations of the State and forwards the request to the state object for processing.

Client:

MusicContext musicCtx = new MusicContext(new HashMap<String, List<String>>() {
{
put("bliss", new ArrayList<String>() {
{
add("Let it be");
add("Happy happy");
}
});
put("depress", new ArrayList<String>() {
{
add("Knife on");
add("Bad day");
}
});
}
});

musicCtx.setState(new BlissfulState());
musicCtx.doPlay();

Context and state classes:


interface MusicState {

public void doPlay(MusicContext ctx);
}

class BlissfulState implements MusicState {
public void doPlay(MusicContext ctx) {
println(ctx.getMusicDB().get("bliss").get(ThreadLocalRandom.current().nextInt(0, 2)));
}
}

class DepressedState implements MusicState {
public void doPlay(MusicContext ctx) {
println(ctx.getMusicDB().get("depress").get(ThreadLocalRandom.current().nextInt(0, 2)));
}
}

class MusicContext {

MusicState myState;

private Map<String, List<String>> musicDB;

MusicContext(Map<String, List<String>> musicDB) {
this.setMusicDB(musicDB);
if (myState == null)
setState(new BlissfulState());
}

public void setState(final MusicState newState) {
myState = newState;
}

public void doPlay() {
myState.doPlay(this);
}

public Map<String, List<String>> getMusicDB() {
return musicDB;
}

public void setMusicDB(Map<String, List<String>> musicDB) {
this.musicDB = musicDB;
}
}

Another approach:

/**
* in the above case the states themselves aren't directly related the control
* to change the state is given to the external program
* 
* but if the state is to be maintained internally then we use an abstract class
* instead of interface and create final state objects.
* 
* the abstract class then will have a protected constructor.
**/

abstract class State {
static State initialState;
static final State state1 = new State1();
static final State state2 = new State2();

protected State() {
if (initialState == null)
initialState = this;
}

abstract void stateExit(StateContext owner);

abstract void stateEnter(StateContext owner);
}

class State1 extends State {
void stateExit(StateContext owner) {
}

void stateEnter(StateContext owner) {
}
}

class State2 extends State {
void stateExit(StateContext owner) {
}

void stateEnter(StateContext owner) {
}
}

class StateContext {

private State stateVar;

// Create the object and initialize its state
public StateContext() {
this.stateVar = State.state1;
stateVar.stateEnter(this);
}

// Set the new state
public void setState(State newState) {
stateVar.stateExit(this);
this.stateVar = newState;
stateVar.stateEnter(this);
}
}


Visitor pattern

is used when we have to perform an operation on a group of similar kind of Objects. With the help of visitor pattern, we can move the operational logic from the objects to another class.
For example, think of a Shopping cart where we can add different type of items (Elements), when we click on checkout button, it calculates the total amount to be paid.

Client:

ItemElement[] cart = new ItemElement[] { new Book(20, "1234"), 
new Book(100, "5678"), 
new Eatables(10, 2), 
new Eatables(5, 5) };
int total = calculatePrice(cart);
println("Total Cost = " + total);

private static int calculatePrice(ItemElement[] items) {
ShoppingCartVisitor visitor = new ShoppingCartVisitorImpl();
int sum = 0;
for (ItemElement item : items) {
sum = sum + item.accept(visitor);
}
return sum;
}



interface ItemElement {
public int accept(ShoppingCartVisitor visitor);
}

class Book implements ItemElement {
private int price;
private String isbnNumber;

public Book(int cost, String isbn) {
this.price = cost;
this.isbnNumber = isbn;
}

public int getPrice() {
return price;
}

public String getIsbnNumber() {
return isbnNumber;
}

@Override
public int accept(ShoppingCartVisitor visitor) {
return visitor.visit(this);
}
}

class Eatables implements ItemElement {
private int pricePerKg;
private int weight;

public Eatables(int priceKg, int wt) {
this.pricePerKg = priceKg;
this.weight = wt;
}

public int getPricePerKg() {
return pricePerKg;
}

public int getWeight() {
return weight;
}

@Override
public int accept(ShoppingCartVisitor visitor) {
return visitor.visit(this);
}
}

interface ShoppingCartVisitor {
int visit(Book book);
int visit(Eatables fruit);
}

class ShoppingCartVisitorImpl implements ShoppingCartVisitor {
@Override
public int visit(Book book) {
int cost = 0;
// apply 5$ discount if book price is greater than 50
if (book.getPrice() > 50) {
cost = book.getPrice() - 5;
} else
cost = book.getPrice();
println("Book ISBN::" + book.getIsbnNumber() + " cost =" + cost);
return cost;
}

@Override
public int visit(Eatables fruit) {
int cost = fruit.getPricePerKg() * fruit.getWeight();
println(" cost = " + cost);
return cost;
}
}

Another interesting example: JavaWorld-Java-Tip-98-Article

Interpreter pattern

is used to define a grammatical representation for a language and provides an interpreter to deal with this grammar.

Client:


String expression = "w x z - +";
Evaluator sentence = new Evaluator(expression);
Map<String,Expression> variables = new HashMap<String,Expression>();
variables.put("w", new Number(5));
variables.put("x", new Number(10));
variables.put("z", new Number(42));
int result = sentence.interpret(variables);
System.out.println(result);


interface Expression {
public int interpret(Map<String,Expression> variables);
}

class Number implements Expression {
private int number;
public Number(int number)       { this.number = number; }
public int interpret(Map<String,Expression> variables)  { return number; }
}

class Plus implements Expression {
Expression leftOperand;
Expression rightOperand;
public Plus(Expression left, Expression right) { 
leftOperand = left; 
rightOperand = right;
}

public int interpret(Map<String,Expression> variables)  { 
return leftOperand.interpret(variables) + rightOperand.interpret(variables);
}
}

class Minus implements Expression {
Expression leftOperand;
Expression rightOperand;
public Minus(Expression left, Expression right) { 
leftOperand = left; 
rightOperand = right;
}

public int interpret(Map<String,Expression> variables)  { 
return leftOperand.interpret(variables) - rightOperand.interpret(variables);
}
}

class Variable implements Expression {
private String name;
public Variable(String name)       { this.name = name; }
public int interpret(Map<String,Expression> variables)  { 
if(null==variables.get(name)) return 0; //Either return new Number(0).
return variables.get(name).interpret(variables); 
}
}

class Evaluator implements Expression {
private Expression syntaxTree;

public Evaluator(String expression) {
Stack<Expression> expressionStack = new Stack<Expression>();
for (String token : expression.split(" ")) {
if  (token.equals("+")) {
Expression subExpression = new Plus(expressionStack.pop(), expressionStack.pop());
expressionStack.push( subExpression );
}
else if (token.equals("-")) {
// it's necessary remove first the right operand from the stack
Expression right = expressionStack.pop();
// ..and after the left one
Expression left = expressionStack.pop();
Expression subExpression = new Minus(left, right);
expressionStack.push( subExpression );
}
else                        
expressionStack.push( new Variable(token) );
}
syntaxTree = expressionStack.pop();
}

public int interpret(Map<String,Expression> context) {
return syntaxTree.interpret(context);
}
}

JDK:
java.util.Pattern and
subclasses of java.text.Format



Iterator pattern

Provides a way to access the elements of an aggregate object without exposing its underlying representation.

List<Integer> list = new ArrayList<Integer>();
list.add(2);list.add(40);

Iterator<Integer> it = list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}

Structural Design Patterns


Adapter pattern

It’s used so that two unrelated interfaces can work together. The object that joins these unrelated interface is called an Adapter.


interface Draw {
	public void draw();
}

class Circle implements Draw {

	@Override
	public void draw() {
		println("Drawing a circle");
	}
}


interface Polygon {
	public void getSides();
	public void getArea();
}

class Square implements Polygon {

	int length;

	Square(int length){
		this.length = length;
	}

	@Override
	public void getSides() {
		println("Sides: 4");
	}

	@Override
	public void getArea() {
		println("Area: "+length*length);
	}
}


Client:

Draw drawingObj = null;

drawingObj = new Circle();
drawingObj.draw();

//Now lets say the client wants to draw a Square but it
//doesn't implement Draw
//drawingObj = new Square();
//drawingObj.draw() //this is not possible so we write a adapter

//in case of object adapters
drawingObj = new SquareAdapter(new Square(5));
drawingObj.draw();
((SquareAdapter) drawingObj).getSquare().getSides();
((SquareAdapter) drawingObj).getSquare().getArea();

//in case of inherited adapters
drawingObj = new SquareAdapter(5);
drawingObj.draw();
((Square) drawingObj).getSides();
((Square) drawingObj).getArea();


Object composition adapters


class SquareAdapter implements Draw {

	Polygon square;

	public SquareAdapter(Polygon square){
		this.square = square;
	}

	@Override
	public void draw(){
		println("Drawing a square");
	}

	public Polygon getSquare() {
		return square;
	}
}

Class inheritance adapters


class SquareAdapter extends Square implements Draw {

	SquareAdapter(int length) {
		super(length);
	}

	@Override
	public void draw(){
		println("Drawing a square");
	}
}
Output:
[main] Drawing a circle [main] Drawing a square [main] Sides: 4 [main] Area: 25
JDK: java.util.Arrays#asList() java.io.InputStreamReader(InputStream) (returns a Reader) java.io.OutputStreamWriter(OutputStream) (returns a Writer) Composite pattern is used when we have to represent a part-whole hierarchy. When we need to create a structure in a way that the objects in the structure has to be treated the same way. Client:

//Initialize leafs ellipses
Ellipse ellipse1 = new Ellipse();
Ellipse ellipse2 = new Ellipse();
Ellipse ellipse3 = new Ellipse();

Hexagon hexagon1 = new Hexagon();
Hexagon hexagon2 = new Hexagon();


//Initialize composite graphics
CompositeGraphic graphic = new CompositeGraphic();
CompositeGraphic graphic1 = new CompositeGraphic();
CompositeGraphic graphic2 = new CompositeGraphic();

//Composes the graphics
graphic1.add(ellipse1);
graphic1.add(ellipse2);
graphic1.add(ellipse3);
graphic2.add(hexagon1);
graphic2.add(hexagon2);

graphic.add(graphic1);
graphic.add(graphic2);

//Prints the complete graphic (four times the string "Ellipse").
graphic.print();

/** "Component" */
interface Graphic {

    //Prints the graphic.
    public void print();
}

/**
 * "Composite" 
 * Composite class usually contains a container for Components (list or tree or..)
 * Composite class usually has 3 operations 
 * 1. add objects to the composite 
 * 2. remove objects, iterate objects
 * 3. perform some operation on all or subset of the objects
 */
class CompositeGraphic implements Graphic {

    //Collection of child graphics.
    private List childGraphics = new ArrayList();

    //Prints the graphic.
    public void print() {
        for (Graphic graphic : childGraphics) {
            if(graphic instanceof CompositeGraphic) {
            	System.out.println("> ");
            	graphic.print();
            }
            else
            	graphic.print();
        }
    }

    //Adds the graphic to the composition.
    public void add(Graphic graphic) {
        childGraphics.add(graphic);
    }

    //Removes the graphic from the composition.
    public void remove(Graphic graphic) {
        childGraphics.remove(graphic);
    }
}

/** A "Leaf" Type */
class Ellipse implements Graphic {

    //Prints the graphic.
    public void print() {
        System.out.println("Ellipse");
    }
}

/** Another "Leaf" Type */
class Hexagon implements Graphic {

    //Prints the graphic.
    public void print() {
        System.out.println("Hexagon");
    }
}
JDK: Lots of Data structures like trees follow this design. java.awt.Container#add(Component) Proxy pattern Provide a surroage or placeholder for another object to control access to it Client:

CommandExecutor cmdExec = new CommandExecutorImpl();
cmdExec.runCommand("rm");

//to force any client to use restricted access
//do not expose CommandExecutorImpl class to the client instead expose
//the proxy class

CommandExecutor cmdExecProxy = new CommandExecutorProxy("supr", "asdf");
cmdExecProxy.runCommand("rm");

interface CommandExecutor {
	public void runCommand(String cmd);
}

class CommandExecutorImpl implements CommandExecutor {

	@Override
	public void runCommand(String cmd) {
		println("Running command: " + cmd);

	}
}


class CommandExecutorProxy implements CommandExecutor {
	private CommandExecutor executor;

	public CommandExecutorProxy(String user, String pwd) {
		// authenticate that the user has privileges
		// if he doesn't have then don't create the
		// dummy impl follows
		if ("super".equals(user) && pwd != null) {
			executor = new CommandExecutorImpl();
		}

	}

	@Override
	public void runCommand(String cmd) {
		if (cmd.trim().startsWith("rm")) {
			// not allowed for any user using the proxy
			println("not allowed");
		} else {
			executor.runCommand(cmd);
		}
	}
}
JDK: Java RMI Flyweight pattern Is used when we need to create a lot of Objects of a class. Since every object consumes memory space that can be crucial for low memory devices Intrinsic properties make the Object unique whereas extrinsic properties are set by client code and used to perform different operations. In below example there are no extrinsic properties. This pattern generally uses factory pattern within itself. Client:

Image img1 = ImageFactory.getImage(ImageType.jpeg);
img1.drawImage();

Image img2 = ImageFactory.getImage(ImageType.jpeg);
img2.drawImage();

Image img3 = ImageFactory.getImage(ImageType.jpeg);
img3.drawImage();

interface Image {
	public void drawImage();
}

class JPEGImage implements Image {

	JPEGImage(){
		println("creating a jpeg image");
		//a sleep added to mean that it's a heavy creation process
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void drawImage() {
		println("drawing jpeg image");
	}
}

class GIFImage implements Image {

	GIFImage(){
		println("creating a gif image");
		//a sleep added to mean that it's a heavy creation process
		try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void drawImage() {
		println("drawing gif image");
	}
	
}

enum ImageType {
	jpeg, gif;
}

class ImageFactory {
	
	public static final Map cache = new HashMap();
	
	public static Image getImage(ImageType imageType) {
		Image image = cache.get(imageType);
		if (image == null) {
			if (imageType.equals(ImageType.jpeg)) {
				image = new JPEGImage();
			} else if (imageType.equals(ImageType.gif)) {
				image = new GIFImage();
			}
			cache.put(imageType, image);
		}
		return image;
	}
}
JDK: wrapper classes valueOf in JDK java string pool Facade pattern Provide a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use. Client:

Shape shape = new Shape();
shape.draw("circle");
shape.draw("square");
shape.draw("square");

class Circle {
	
	public void drawCircle(){
		println("draws a circle");
	}
}

class Square {
	
	public void drawSquare() {
		println("draws a square");
	}
}


//both circle and square classes come from different sources
//they are clossed to modification
//now we create a common interface for accessing both

class Shape {
	Circle circle;
	Square square;

	public void draw(String type) {
		if (type.equals("circle")) {
			if(circle==null)
				circle = new Circle();
			circle.drawCircle();
		} else {
			if(square==null)
				square = new Square();
			square.drawSquare();
		}

	}
}
Decorator pattern We use inheritance or composition to extend the behavior of an object but this is done at compile time and its applicable to all the instances of the class. We can’t add any new functionality of remove any existing behavior at runtime – this is when Decorator pattern comes into picture. Client:

int c;
try {
	InputStream in = new LowerCaseInputStream(new BufferedInputStream(new FileInputStream("test.txt")));

	while ((c = in.read()) >= 0) {
		System.out.print((char) c);
	}

	in.close();
} catch (IOException e) {
}

class LowerCaseInputStream extends FilterInputStream {
	public LowerCaseInputStream(InputStream in) {
		super(in);
	}

	public int read() throws IOException {
		int c = super.read();
		return (c == -1 ? c : Character.toLowerCase((char) c));
	}
}

Creational Design Patterns


Singleton pattern

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.

So instead of doing
Worker worker = new Worker(); 
in your client. You should be doing this.

Worker worker = Worker.getInstance();
worker.doWork();
worker = Worker.getInstance();
worker.doWork();

Eager Initialization - the instance of Singleton Class is created at the time of class loading


class Worker {

	private static final Worker instance = new Worker();

	private int counter = 0;

	private Worker() {
		println("worker initialized");
	}

	public static Worker getInstance() {
		return instance;
	}

	public void doWork() {
		println("counter: "+counter++);
	}
}


Static block Initialization - another way of eager initialization, the instance of Singleton Class is created at the time of class loading


class Worker {

    private static final Worker instance;

	private int counter = 0;

    static {
        try {
            instance = new Worker();
        } catch (Exception e) {
            throw new RuntimeException("Exception occured in creating singleton instance");
        }
    }

    private Worker() {
        println("worker initialized");
    }

    public static Worker getInstance() {
        return instance;
    }

    public void doWork() {
        println("counter: "+counter++);
    }
}


Lazy Initialization


class Worker {

	private static Worker instance;

	private int counter = 0;

	private Worker() {
		println("worker initialized");
	}

	public static Worker getInstance() {
		if(instance == null) {
			instance = new Worker();
		}
		return instance;
	}

	public void doWork() {
		println("counter: "+counter++);
	}
}


Thread safe singleton


class Worker {

	private static Worker instance;

	private int counter = 0;

	private Worker() {
		println("worker initialized");
	}

	public static synchronized Worker getInstance() {
		if(instance == null) {
			instance = new Worker();
		}
		return instance;
	}

	public void doWork() {
		println("counter: "+counter++);
	}
}


Thread safe - double checked locking - it avoid unnecessary wait on the lock on the method


class Worker {

	private static Worker instance;

	private int counter = 0;

	private Worker() {
		println("worker initialized");
	}

	public static Worker getInstance() {
		if(instance == null) {
			synchronized (Worker.class) {
				if(instance == null) {
					instance = new Worker();
				}
			}
		}
		return instance;
	}

	public void doWork() {
		println("counter: "+counter++);
	}
}


Initialization-On-Demand Holder (Bill Pugh)

Prior to Java 5, java memory model had a lot of issues and above approaches used to fail in certain scenarios where too many threads try to get the instance of the Singleton class simultaneously.
This is lazy at the sametime thread safe.

As the class initialization phase is guaranteed by the JLS to be serial,
i.e., non-concurrent, so no further synchronization is required in the static getInstance() method during loading and initialization.


class WorkerHelper {

	public static Worker getInstance() {
		return Worker.instance;
	}

	private static class Worker {

		private int counter = 0;

		private static final Worker instance = new Worker();

		private Worker() {
			println("worker initialized");
		}

		public void doWork() {
			println("counter: "+counter++);
		}
	}

}

Reflection can be used to destroy all the above singleton implementation approaches but enums overcome this situation


Enums - Singletons on steroids


enum Worker {

	instance;

	private int counter=0;

	public void doWork() {
		println("counter: "+counter++);
	}
}


Factory pattern

Client:

Animal dog = AnimalFactory.createAnimal("Dog");
println(dog.toString());

Factory and implementation:

class AnimalFactory {

	public static Animal createAnimal(String type) {
		Animal animal = null;
		if("Dog".equals(type)){
			animal = new Dog("Boxi");
			return animal;
		}
		return animal;
	}
}

abstract class Animal {

	private String name;

	public abstract String getType();

	public String toString(){
		return "Type: "+getType()+", Name: "+getName();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}


class Dog extends Animal {

	Dog(String name){
		setName(name);
	}

	@Override
	public String getType() {
		return "Dog";
	}
}
Output:
[main] Type: Dog, Name: Boxi
Examples within JDK: Calender ResourceBundle NumberFormat Abstract Factory pattern Client:

AnimalFactory factory = new DogFactory();
Animal dog = factory.createAnimal();
println(dog.toString());
Factory and impl:

interface AnimalFactory {
	Animal createAnimal();
}


class DogFactory implements AnimalFactory {
	public Animal createAnimal(){
		return new Dog("Boxi");
	}
}

abstract class Animal {

	private String name;

	public abstract String getType();

	public String toString(){
		return "Type: "+getType()+", Name: "+getName();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}


class Dog extends Animal {

	Dog(String name){
		setName(name);
	}

	@Override
	public String getType() {
		return "Dog";
	}
}
Examples within JDK: javax.xml.parsers.DocumentBuilderFactory javax.xml.transform.TransformerFactory javax.xml.xpath.XPathFactory Builder pattern when the Object contains a lot of attributes. Using default values and lots of setters in factory pattern gets complex or sometimes inconsistent. Client:

Dog dog = new DogBuilder().setColor("black").setWeight("10kg").build();
println(dog.toString());

abstract class Animal {

	private String name;

	public abstract String getType();

	public String toString(){
		return "Type: "+getType()+", Name: "+getName();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}


class Dog extends Animal {

	private String color;
	private String weight;

	//Dog class exposes only one public constructor and that takes in a DogBuilder
	//Any other constructor is usually made private

	Dog(DogBuilder builder) {
		this.color = builder.color;
		this.weight =  builder.weight;
	}

	@Override
	public String getType() {
		return "Dog";
	}

	public String getColor() {
		return color;
	}

	public String getWeight() {
		return weight;
	}

	public String toString(){
		return super.toString()+", Color: "+getColor()+", Weight: "+getWeight();
	}

	//We don't provide the setters on the Dog class
	//As that is taken care by the DogBuilder
	//any other business logic related to building a Dog class goes into it's builder

	static class DogBuilder {

		String color;
		String weight;

		public DogBuilder setColor(String color) {
			this.color = color;
			return this;
		}

		public DogBuilder setWeight(String weight) {
			this.weight = weight;
			return this;
		}

		public Dog build() {
			return new Dog(this);
		}
	}
}
JDK: java.lang.StringBuilder#append() java.lang.StringBuffer#append() Prototype pattern when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing. So this pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. Client:

Animals animals = new Animals();
animals.loadNames();
println(animals.getNames());
Animals new_animals = (Animals)animals.clone();
//you don't have to call loadNames again because that data
//too is cloned into the object
println(new_animals.getNames());

class Animals implements Cloneable {

	private List names;

	Animals() {
		names = new ArrayList();
	}

	public String toString(){
		return "Name: "+getNames();
	}

	public List getNames() {
		return names;
	}

	public void setNames(List names) {
		this.names = names;
	}

	public void loadNames() {
		//reads data from some data source like DB into list
		names.add("boxi");
		names.add("peggy");
		names.add("blacky");
	}

	@Override
	public Object clone() throws CloneNotSupportedException {

		Animals animals = new Animals();

		//this stores the same reference to list - don't do this - this is not deep copy
		//animals.setNames(names);

		//this is deep copy
		List temp = new ArrayList();
		for(String name: getNames()){
			temp.add(name);
		}
		animals.setNames(temp);

		return animals;
	}
}

Servlets and JSP caching in Websphere


The servlet/JSP caching facility will catch the response from servlet/JSP invocation and cache the HTML results. Servlets are configured for caching via entries in the cachespec.xml file (described here). They can be designated by their URI path, or by classname. The latter option is more inclusive, since it will catch any invocation of the servlet regardless of the aliases. In most cases, the cache entry for the servlet needs to be further qualified by additional inputs, such as the request parameters or values from the user session information. We will explain this further in our section on specifying cache entries.

When preparing to execute a servlet, the dynacache engine filters the service() method of each servlet that is about to be executed, and determines if this matches any cache ID entries based on the parameters present. If a match is found, the cached results are returned rather than executing the service() method and all of the work that would have been done beyond it. This avoids all of the processing that would have been done by the servlet, resulting in a substantial performance boost. If there is not a cache entry for this ID, the service() method is executed as normal and the results are caught and placed in the cache before they are returned to the user.


Sample cachespec.xml file for a JSP

<cache>
   <cache-entry>
      <class>servlet</class>              
      <name>/displayForecast.jsp</name>
      <property name="EdgeCacheable">true</property>
      <cache-id>
         <component id="zip" type="parameter">
            <required>true</required>
         </component>
         <priority>3</priority>
         <timeout>20</timeout>
      </cache-id>
   </cache-entry>
</cache>

Above is a simple cachespec.xml file with a single cache entry for a JSP. You might notice that the class is servlet, while the name clearly identifies a JSP. This is because JSPs are compiled into servlets on the backend, so from the application server's perspective, they are essentially the same thing. This JSP has a property that states that it is "edge cacheable".

Notice that the cache ID is composed of a single request parameter, the zip code for the forecast. This means that if seven users request forecasts for seven different zip codes, there will be seven cache entries in the cache with the zip code serving as their key. Subsequent users requesting forecasts for any of these seven zip codes will be served up the forecast for the appropriate area. This cache entry has been configured with a priority of 3, meaning it gets three "free passes" if it is designated as ready to be invalidated by the LRU algorithm, mentioned earlier in our discussion on invalidation. The entry is set to a default timeout of 20 seconds; however, it could be invalidated earlier by means of a program API, another cache entry that is designated to invalidate it, or purging due to a full cache.