TCP stands for Transmission Control Protocol and UDP stands for User Datagram Protocol, and both are used extensively to build Internet applications.
The protocol which is the core of internet, HTTP is based on TCP.
why
why Java developer should understand these two protocols in detail is that Java is extensively used to write multi-threaded, concurrent and scalable servers.
where
While UDP is more suitable for applications that need fast, efficient transmission, such as games. UDP’s stateless nature is also useful for servers that answer small queries from huge numbers of clients. In practice, TCP is used in finance domain e.g. FIX protocol is a TCP based protocol, UDP is used heavily in gaming and entertainment sites.
how
TCP is connection oriented, reliable, slow, provides guaranteed delivery and preserves the order of messages
UDP is connectionless, unreliable, no ordering guarantee, but a fast protocol.
TCP overhead is also much higher than UDP, as it transmits more metadata per packet than UDP. that header size of Transmission control protocol is 20 bytes, compared to 8 bytes header of User Datagram protocol.
Use TCP, if you can’t afford to lose any message, while UDP is better for high-speed data transmission, where loss of a single packet is acceptable e.g. video streaming or online multiplayer games.
public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled){ this.isGraphicsCardEnabled = isGraphicsCardEnabled; returnthis; }
public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled){ this.isBluetoothEnabled = isBluetoothEnabled; returnthis; }
public Computer build(){ returnnew Computer(this); }
} }
//ComputerBuilder
import com.journaldev.design.builder.Computer;
publicclassTestBuilderPattern{
publicstaticvoidmain(String[] args){ //Using builder to get the object in a single line of code and //without any inconsistent state or arguments management issues Computer comp = new Computer.ComputerBuilder( "500 GB", "2 GB").setBluetoothEnabled(true) .setGraphicsCardEnabled(true).build(); } } ```
ORM is an acronym for Object/Relational mapping. It is a programming strategy to map object with the data stored in the database. It simplifies data creation, data manipulation, and data access.
The advantages of using ORM over JDBC
Application development is fast.
Management of transaction.
Generates key automatically.
Details of SQL queries are hidden.
Hibernate Architecture
Java application layer
Hibernate framework layer
Backhand api layer
Database layer
Hibernate Application Architecture:
JDBC (Java Database Connectivity)
JTA (Java Transaction API)
JNDI (Java Naming Directory Interface)
Elements of Hibernate Architecture
Configuration
Database Connection − This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
Class Mapping Setup − This component creates the connection between the Java classes and database tables.
SessionFactory
SessionFactory is a thread-safe object, many threads cannot access it simultaneously.
Session
It maintains a connection between the hibernate application and database.It provides methods to store, update, delete or fetch data from the database such as persist(), update(), delete(), load(), get() etc.
Session is not a thread-safe object, many threads can access it simultaneously. In other words, you can share it between threads.
Transaction
ConnectionProvider
Query
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.
Criteria
Criteria objects are used to create and execute object oriented criteria queries to retrieve objects.
About SQL
SQL query created in Hibernate(Native sql)
Session.createSQLQuery
1 2 3
Session.createSQLQuery() //The method createSQLQuery() creates Query object using the native SQL syntax. Query query = session.createSQLQuery("Select * from Student");
HQL query
Session.createQuery
1 2 3
Session.createQuery() //The method createQuery() creates Query object using the HQL syntax. Query query = session.createQuery("from Student s where s.name like 'k%'");
criteria query
Session.createCriteria
1 2 3
Session.createCriteria() //The method createCriteria() creates Criteria object for setting the query parameters. This is more useful feature for those who don't want to write the query in hand. You can specify any type of complicated syntax using the Criteria API. Criteria criteria = session.createCriteria(Student.class);
HQL vs Criteria
HQL is to perform both select and non-select operations on the data, but Criteria is only for selecting the data, we cannot perform non-select operations using criteria
HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries
HQL doesn’t support pagination concept, but we can achieve pagination with Criteria
Criteria used to take more time to execute then HQL
With Criteria we are safe with SQL Injection because of its dynamic query generation but in HQL as your queries are either fixed or parametrized, there is no safe from SQL Injection.
Caching
Cache memory stores recently used data items in order to reduce the number of database hits as much as possible.
First level Cache
Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely.Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.
Second level Cache
Hibernate Second Level cache is disabled by default but we can enable it through configuration. Currently EHCache and Infinispan provides implementation for Hibernate Second level cache and we can use them.
Query Cache
Hibernate can also cache result set of a query. Hibernate Query Cache doesn’t cache the state of the actual entities in the cache; it caches only identifier values and results of value type. So it should always be used in conjunction with the second-level cache.
Delete all keys from all Redis databases: `$ redis-cli FLUSHALL` Delete all keys of the currently selected Redis database: `$ redis-cli FLUSHDB` Delete all keys of the specified Redis database: `$ redis-cli -n <database_number> FLUSHDB`
删除指定前缀的数据
1 2
# 删除指定CCR866前缀的redis数据 path/to/redis-cli -p 16379 -a Redis6379 -n 1 keys 'CCR866*' | xargs ./redis-cli -p 16379 -a Redis6379 -n 1 del
Java is every where in browser, in mobile, in TV or in set-top boxes and if you are into Java programming language than you know that Java code which is bundled in JAR (Java archive) file require Java virtual machine JVM to execute it.
JVM: java virtual machine
Java Virtual Machine is get created when you run a java program using java command e.g. java HelloWorld. JVM is responsible for converting byte code into machine specific code
JDK: java development kit
JDK is also loosely referred as JRE but its lot more than JRE and it provides all the tools and executable require to compile debug and execute Java Program.
basic architecture of the JVM
Class Loader Sub System
1. Loading
loading the class file and store inside method area
Created object is not student object or customer object. It is a predefined class “Class” object that is presently in java.lang package.
For every loaded .class file, only one class “Class” object will be created by JVM, even though we are using that class multiple times in our program. Example,
2. Linking
verification
This Byte Code Verifier is responsible to verify weather .class file is properly formatted or not, structurally correct or not, generated by valid compiler or not.
preparation
allocate memory for class level static variables and assigned default values.
E.g. For int —> 0, For double —> 0.0, For boolean —> false
Resolution
It is the process of replacing all symbolic references used in our class with original direct references from method area.
Initialization
In Initialization activity, for class level static variables assigns original values and static blocks will be executed from top to bottom.
Types of class loaders in class loader subsystem
Bootstrap class loader/ Primordial class loader
Extension class loader
Application class loader/System class loader
3. Class loader sub system follows delegation hierarchy algorithm
Customized class loaderSometimes we may not satisfy with default class loader mechanism then we can go for Customized class loader. For example:
Various Memory Areas in JVM
1. Method Area
Inside method area class level binary data including static variables will be stored
Constant pools of a class will be stored inside method area.
Method area can be accessed by multiple threads simultaneously.
All threads share the same method area, so access to the method area’s data structures must be designed to be thread-safe.
2. Heap Area
Heap space in Java is used for dynamic memory allocation for Java objects and JRE classes at the runtime. New objects are always created in heap space and the references to this objects are stored in stack memory.
These objects have global access and can be accessed from anywhere in the application.
This memory model is further broken into smaller parts called generations, these are:
Young Generation – this is where all new objects are allocated and aged. A minor Garbage collection occurs when this fills up
Old or Tenured Generation – this is where long surviving objects are stored. When objects are stored in the Young Generation, a threshold for the object’s age is set and when that threshold is reached, the object is moved to the old generation
Permanent Generation – this consists of JVM metadata for the runtime classes and application methods
It’s accessed via complex memory management techniques that include Young Generation, Old or Tenured Generation, and Permanent Generation
If heap space is full, Java throws java.lang.OutOfMemoryError
Access to this memory is relatively slower than stack memory
This memory, in contrast to stack, isn’t automatically deallocated. It needs Garbage Collector to free up unused objects so as to keep the efficiency of the memory usage
Unlike stack, a heap isn’t threadsafe and needs to be guarded by properly synchronizing the code
Objects and corresponding instance variables will be stored in the heap area.
Every array in java is object only hence arrays also will be stored in the heap area.
Heap area can be access by multiple threads and hence the data stored in the heap area is not thread safe.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Set Maximum and Minimum heap size -Xmx To set maximum heap size , i.e., maxMemory java -Xmx512m HeapSpaceDemo Here mx = maximum size 512m = 512 MB HeapSpaceDemo = Java class name -Xms To set minimum heap size , i.e., total memory java -Xms65m HeapSpaceDemo Here ms = minimum size 65m = 65 MB HeapSpaceDemo = Java class name or, you can set a minimum maximum heap size at a time java -Xms256m -Xmx1024m HeapSpaceDemo
3. Stack Memory
Stack Memory in Java is used for static memory allocation and the execution of a thread. It contains primitive values that are specific to a method and references to objects that are in a heap, referred from the method.
1 2 3
Access to this memory is in Last-In-First-Out (LIFO) order. Whenever a new method is called, a new block on top of the stack is created which contains values specific to that method, like primitive variables and references to objects.
When the method finishes execution, it’s corresponding stack frame is flushed, the flow goes back to the calling method and space becomes available for the next method.
It grows and shrinks as new methods are called and returned respectively
Variables inside stack exist only as long as the method that created them is running
It’s automatically allocated and deallocated when method finishes execution
If this memory is full, Java throws java.lang.StackOverFlowError
Access to this memory is fast when compared to heap memory
This memory is threadsafe as each thread operates in its own stack
Local Variable Array
It contains all parameters and local variables of the method.
the occupied slot
Operand Stack
JVM uses operand stack as work space.
last-in first-out (LIFO)
how a Java virtual machine would add two local variables that contain ints and store the int result in a third local variable:
Frame Data
Stack Memory vs Heap Space
Parameter
Stack Memory
Heap Space
Application
Stack is used in parts, one at a time during execution of a thread
The entire application uses Heap space during runtime
Size
Stack has size limits depending upon OS and is usually smaller then Heap
There is no size limit on Heap
Storage
Stores only primitive variables and references to objects that are created in Heap Space
All the newly created objects are stored here
Order
It is accessed using Last-in First-out (LIFO) memory allocation system
This memory is accessed via complex memory management techniques that include Young Generation, Old or Tenured Generation, and Permanent Generation.
Life
Stack memory only exists as long as the current method is running
Heap space exists as long as the application runs
Efficiency
Comparatively much faster to allocate when compared to heap
Slower to allocate when compared to stack
Allocation/Deallocation
This Memory is automatically allocated and deallocated when a method is called and returned respectively
Heap space is allocated when new objects are created and deallocated by Gargabe Collector when they are no longer referenced
4. PC Registers(Program Counter Registers)
For every thread a separate PC register will be created at the time of thread creation. PC register contains address of current executing instruction. Once instruction execution completes automatically PC register will be incremented to hold address of next instruction. An “address” can be a native pointer or an offset from the beginning of a method’s byte codes.
5. Native Method Stacks
Here also for every Thread a separate run time stack will be created. It contains all the native methods used in the application. Native method means methods written in a language other than the Java programming language. In other words, it is a stack used to execute C/C++ codes invoked through JNI (Java Native Interface). According to the language, a C stack or C++ stack is created.
Execution Engine
1. Interpreter
It is responsible to read byte code and interpret into machine code (native code) and execute that machine code line by line.
2. JIT Compiler
The JIT compiler has been introduced to compensate for the disadvantages of the interpreter. The main purpose of JIT compiler is to improve the performance. Internally JIT compiler maintains a separate count for every method. Whenever JVM across any method call, first that method will be interpreted normally by the interpreter and JIT compiler increments the corresponding count variable.
Profiler which is the part of JIT compiler is responsible to identify Hotspot(Repeated Used Methods).
Java Native Interface(JNI)
JNI is acts as a bridge (Mediator) for java method calls and corresponding native libraries.
These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case.
Singleton
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.
different approaches to implement:
Private constructor to restrict instantiation of the class from other classes.
Private static variable of the same class that is the only instance of the class.
Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
//illegal construct //Compile Time Error: The constructor SingleObject() is not visible //SingleObject object = new SingleObject();
//Get the only object available SingleObject object = SingleObject.getInstance();
//show the message object.showMessage(); } }
Factory
Factory design pattern provides approach to code for interface rather than implementation.
Factory pattern removes the instantiation of actual implementation classes from client code. Factory pattern makes our code more robust, less coupled and easy to extend. For example, we can easily change PC class implementation because client program is unaware of this.
Factory pattern provides abstraction between implementation and client classes through inheritance.
Abstract Factory
Abstract Factory design pattern provides approach to code for interface rather than implementation.
Abstract Factory pattern is “factory of factories” and can be easily extended to accommodate more products, for example we can add another sub-class Laptop and a factory LaptopFactory.
Abstract Factory pattern is robust and avoid conditional logic of Factory pattern.
Builder
Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object.
Prototype
Prototype design pattern is used when the Object creation is a costly affair and requires a lot of time and resources and you have a similar object already existing.Prototype pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs. Prototype design pattern uses java cloning to copy the object.
Structural Design Patterns
These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities.
Adapter
Adapter design pattern is one of the structural design pattern and its used so that two unrelated interfaces can work together. The object that joins these unrelated interface is called an Adapter.
Composite
Composite design pattern is used when we have to represent a part-whole hierarchy.
Proxy
Proxy design pattern common uses are to control access or to provide a wrapper implementation for better performance.
Flyweight
Use sharing to support large numbers of fine-grained objects efficiently
Facade
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.
Bridge
Decouple an abstraction from its implementation so that the two can vary independently.
Decorator
Decorator design pattern is helpful in providing runtime modification abilities and hence more flexible. Its easy to maintain and extend when the number of choices are more.
The disadvantage of decorator design pattern is that it uses a lot of similar kind of objects (decorators).
Behavioral Design Patterns
These design patterns are specifically concerned with communication between objects.
Template Method
Template method should consists of certain steps whose order is fixed and for some of the methods, implementation differs from base class to subclass. Template method should be final.
Most of the times, subclasses calls methods from super class but in template pattern, superclass template method calls methods from subclasses, this is known as Hollywood Principle – “don’t call us, we’ll call you.”.
Methods in base class with default implementation are referred as Hooks and they are intended to be overridden by subclasses, if you want some of the methods to be not overridden, you can make them final, for example in our case we can make buildFoundation() method final because if we don’t want subclasses to override it.
Media
Allows loose coupling by encapsulating the way disparate sets of objects interact and communicate with each other. Allows for the actions of each object set to vary independently of one another.