Showing posts with label java notes. Show all posts
Showing posts with label java notes. Show all posts

Thursday, 21 September 2017

Hibernate short notes


  • Transient
  • Persistance
  • Detached


Save() - hibernate function,it will return generated key
Persist() - JPA function works same as save(),return type is void
Merge() - JPA function,return type is void
Update() - hibernate function
saveOrupdate() - hibernate function


Different between session.get() and session.load():-

Actually, both functions are use to retrieve an object with different mechanism, of course.

1. session.load()
• It will always return a “proxy” (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object.
• If no row found , it will throws an ObjectNotFoundException.
2. session.get()
• It always hit the database and return the real object, an object that represent the database row, not proxy.
• If no row found , it return null.

Wednesday, 20 September 2017

Notes on Singleton Pattern and Immutable Objects

Where exactly the Singleton Pattern is used in real application?

  • ·       Logger
  • ·       DB Connection

 A Strategy for Defining Immutable Objects

  1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
  2. Make all fields final and private.
  3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
  4. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    • Don't provide methods that modify the mutable objects.
    • Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

Saturday, 9 September 2017

Lambdas

Lambda basics:-

whay lambdas?
-> helps functional programming

Advantages:-

  • concise code
  • parallel processing

Drawback of oops:
All code blocks should be associated with class and objects.

Lambda Expression examples

(int a) -> a * 2; // Calculate the double of a
a -> a * 2; // or simply without type
(a, b) -> a + b; // Sum of 2 parameters
If the lambda is more than one expression we can use { } and return

(x, y) -> {
int sum = x + y;
int avg = sum / 2;
return avg;
}
A lambda expression cannot stand alone in Java, it need to be associated to a functional interface.

interface MyMath {
    int getDoubleOf(int a);
}

MyMath d = a -> a * 2; // associated to the interface
d.getDoubleOf(4); // is 8

HATEOAS

HATEOAS:- Hypertext As The Engine Of Application State
.
The way of sending the response with links which directs the next possible operations.
{
"name": "Vikram",
"id": 1
"link" [
{
"href":"http://localhost:8080/myApp/1",
"rel":"self"
}
]
}

Richardson maturity Modal:-


Friday, 8 September 2017

Spring Framework Complete

understand the complete flow and add spring security,cloud,log,database change and add an article in dzone. sept 8-10

worked on Spring application pet Clinic accepted as the Reference project for all spring features since 2007.
Github link:- PETCLINIC GITHUB
in Spring site:- link

Its Developed by spring developers and opensource contributors.
Spring-Petclinic is spread accross different repos in github each with different approach to solve the same common requirement.

List of features it explains:-
Spring MVC
  With XMl
  With Annotations+xml
  With JavaConfig
  With JSP UI
  With Thymeleaf UI


Spring Rest - HATEOAS

  With JDBC
  With jpa - EntityManager
  Spring Jpa

For both H2 Database and Mysql.

Spring Rest + Angular JS

Spring boot

Spring Microservices
  Eureka for node register and discovery


Docker 

Thursday, 7 September 2017

Revision Day 7: Multi-threading- synchronized : Class level vs object level

Class level vs object level

Class Level:-

private void lock() throws InterruptedException {
System.out.println(Thread.currentThread().getName());
synchronized (Foo.class) {
System.out.println("in Class  " + Thread.currentThread().getName());
Thread.sleep(4000);
System.out.println("in Class " + Thread.currentThread().getName() + " end");
}

}
main(){
Foo b1 = new Foo();
Thread t1 = new Thread(b1);
Foo b2 = new Foo();
Thread t3 = new Thread(b2);
t1.setName("t1");
t3.setName("t3");
t1.start();
t3.start();
}

Output:-
t1
t3
in Class  t1
in Class t1 end2
in Class  t3
in Class t3 end2

in case of Class level blocking,only one thread can run the class-synchronized method at a time,Also to note an instance synchronized method can also run simultaneously

As seen above eventhough t1 and t3 entered the block at the same time,only after completion of t1, t3 can start accessing the method.

Object Level:-

public void Lock() throws InterruptedException {
System.out.println(Thread.currentThread().getName());
synchronized (this) {
System.out.println("in obj " + Thread.currentThread().getName());
Thread.sleep(4000);
System.out.println("in obj " + Thread.currentThread().getName() + " end");
}
}

main(){
Foo b1 = new Foo();
Thread t1 = new Thread(b1);
Foo b2 = new Foo();
Thread t3 = new Thread(b2);
t1.setName("t1");
t3.setName("t3");
t1.start();
t3.start();
}

Output:-
t1
t3
in obj t1
in obj t3
in obj t3 end
in obj t1 end

In case of instance synchronized method,both t1 and t3 can start accessing the method at the same time because both are acting on 2 different objects.

Tuesday, 5 September 2017

Notes on Threads and Multi-threading Application

MultiThread Project takes the directory as input,and gives the PDF and TXT files with their size,name and path.

Github path:- MultiThread_Application

Notes:-

Concurrency 
· BlockingQueue
- interface - extremely useful in producer-consumer problems
o ArrayBlockingQueue,- implementation of BlockingQueue interface
o PriorityBlockingQueue - Same as BlockingQueue but its contents should be comparable either
 naturl ordering or by                 customizing
o DelayQueue - Same as BlockingQueue but its contents can be accessed only after certain time say 5 sec.
o SynchronousQueue - A special type of BlockingQueue with the size of zero.you can insert into it only 
when the consumer is waiting
o LinkedBlockingQueue - linkedlist approach of ArrayBlockingQueue -- implementation of BlockingQueue
 interface
· BlockingDeQueue - Same as BlockingQueue but with Dequque functions
o LinkedBlockingDeque - Same as BlockingQueue but with linkedlist + Dequque functions
· Java Thread Pools
o Executor - Its an interface with execute function.
o Executors Class - its like a factory class that supports all ExecutorService inteface functions.
o ExecutorService - Interface extends Executor class, Executor framework.
o ScheduledExecutorService - creates threads upon specified time.
· ConcurrentMap
o ConcurrentHashMap - HashMap with all methods synchronized
· ConcurrentNavigableMap
o ConcurrentSkipListMap
· ConcurrentSkipListSet
· ConcurrentLinkedQueue
· CopyOnWriteArrays - thread-safe variant of ArrayList - The collection internally copies its contents over 
to a new array upon any modification, so readers accessing the contents of the array incur no synchronization 
costs
· Callable and Future - callable is alternative to Runnable where object has to be returned,and Future is
 going to hold the returned object.
· Condition Class - Condition factors out the Object monitor methods (wait, notify and notifyAll) into distinct 
objects to give the effect of having multiple wait-sets per object, by combining them with the use of arbitrary
 Lock implementations.
· CyclicBarrier - allows multiple threads to wait for each other (barrier) before proceeding.
· CountDownLatch - just a counter need to decrease and call await method till then all threads after the 
current thread are held.
· ReentrantLock Class - alternate to using Synchronized block.
eg:-
private Lock lock = new ReentrantLock();
lock.lock();
try {
increment();
} finally {
lock.unlock();
}

· ReentrantReadWriteLock - ReentrantLock with additional readlock and writeLock functionalities.
· Semaphore - counter is greater than zero, then access is allowed. If it is zero, then access is denied.
use sem.acquire();,sem.release(); to get the permit and release
· Exchanger - an CLass which helps to exchange the classes between threads.

· java.util.concurrent.atomic - increment the integer in synchronized way.

 ExecutorService service = Executors.newFixedThreadPool(4);//total 4 threads availabe in the pool
        new Thread(new FileOperations()).start();        for (int i = 0; i < 2; i++) {
            service.submit(new PDFreader());//2 threads given to PDFReader
        }
        for (int i = 0; i < 2; i++) {
            service.submit(new TxtReader());//2 threads given to TxtReader

        }

Monday, 28 August 2017

Java Notes

Java Technology

HelloWorld.java -> Java Code
HelloWorld.class -> Java ByteCode

Bytecode

Object : -An  real-world object with state and behaviour

Class:- It’s a blueprint from which objects can be created

Class can be public or default.it cannot be declared as private or protected.

Class Name consists of:- alphabets, Numbers, $,_

Inheritance

Extends

Interface – A Contract between a class and the outside world.

Implements

Package

Variables
Instance Variables (Non-Static Fields)
Class Variables (Static Fields)
Local Variables
Parameters


Literals :- Java Literals are syntactic representations of variables.

Using Underscore Characters in Numeric Literals
long creditCardNumber = 1234_5678_9012_3456L; which is equal to 1234567890123456

Array
Java.util.Arrays
Arrays.binarySearch(array,key)
Arrays.fill(array,value)
Arrays.Equals(array1,array2) 1 dimension
Arrays.deepequals(array1,array2) 2 dimension

Operators


Type Comparison Operator instanceof

Bitwise and Bit Shift Operators

<<,<<<,&,|,^

If another class cannot call a Class constructor, it cannot directly create Class objects.

Variable Argument (Varargs)

            private static int add(int... i) {
                        int sum = 0;
                        for (int k = 0; k < i.length; k++) {
                                    sum += i[k];
                        }
                        return sum;
            }

Object Creation of  a class by name myClass:-

new()
myClass.class.newInstance()
Class obj = Class.forName("myClass”);
myClass myclass = obj.getInstance();
Serialization
Clone()


compile-time constant
A constant variable of primitive type or type String that is declared final and initialized with a compile-time constant expression.

Important Nested Classes

Nested classes that are declared static are called static nested classes.
Non-static nested classes are called inner classes.
There are two special kinds of inner classes: local classes and anonymous classes.
a local class can access local variables and parameters of the enclosing block that are final or
effectively final
Shadowing
Local classes are similar to inner classes because they cannot define or declare any static members
Final and Effectively Final:-
A variable or parameter whose value is never changed after it is initialized is effectively final.

Serializable

serialize an object means to convert its state to a byte stream so that the byte stream can be
 reverted back into a copy of the object.
A Java object is serializable if its class or any of its superclasses implements either the
 java.io.Serializable interface or its subinterface, java.io.Externalizable.

Enum

All enums implicitly extend java.lang.Enum.hence they cannot be extended further.
Note: The constructor for an enum type must be package-private or private access. It automatically
creates the constants that are defined at the beginning of the enum body. You cannot invoke an
enum constructor yourself


All interfaces are inherently static
Annotation

Interfaces
abstract methods, default methods, and static methods.
All constant values defined in an interface are implicitly public, static, and final, you can omit
these modifiers.

The Java programming language supports multiple inheritance of type

Using an Interface as a Type

Overriding and Hiding Methods

covariant return type

Instance methods are preferred over interface default methods.

Static methods in interfaces are never inherited.

virtual method invocation

hiding fields
hiding methods

Methods called from constructors should generally be declared final.

Abstract Class Implements an Interface

Abstract calss can have final methods.

static import

Generics

type inference

bounded type parameters

Given two concrete types A and B (for example, Number and Integer), MyClass<A> has no
 relationship to MyClass<B>, regardless of whether or not A and B are related. The common
parent of MyClass<A> and MyClass<B> is Object.

static import

exception

exception handling

call stack

Checked Exceptions
Errors and runtime exceptions are collectively known as unchecked exceptions

All exceptions inherit from Throwable class

If a catch block handles more than one exception type, then the catch parameter is implicitly final.

try-with-resources statement is a try statement that declares one or more resources.
Any object that implements java.lang.AutoCloseable, which includes all objects which implement
 java.io.Closeable, can be used as a resource.

suppressed exceptions

runtime exception  occurs when a method tries to access a member of an object through a null
reference

StackTraceElement

File IO

java.io vs java.nio

Io Streams

Array based memory

byte streams

InputStream and OutputStream are superclasses

FileInputStream and FileOutputStream are descendends of above two classes.Used for byte reading

FileReader and FileWriter same as above used for character’s reading.

BufferedReader and PrintWriter used in Line-Oriented I/O


Buffered Streams


There are four buffered stream classes used to wrap unbuffered streams: BufferedInputStream and
BufferedOutputStream create buffered byte streams, while BufferedReader and BufferedWriter
create buffered character streams.


flushing the buffer.

Datastreams

objectStreams


FileVisitor to walkthrough file tree

Type Erasure and Bridge Methods
       
Restrictions on generics

 ACID (Atomicity, Consistency, Isolation, Durability)

Installing Docker and Minikube

  install docker-   sudo apt install docker.io   set user to docker group:- sudo gpasswd -a   {user} docker   imp commands:- ...