Java
Java
Middleware
Queue/Topic:
- Queue received by only one *receiver*
- Topic broadcasted to multiple *subscribers*
Proxy Servers:
- API Gateway: Dynamically update configuration via API/Web Interface. Acts as a reverse proxy
as well. Provides authentication, rate limiting.
eg. Zuul Proxy
- Reverse Proxy: Between Internet and App Servers. eg. nginx, apache, etc. primarily for load
balancing, caching.
Security:
- Client -> Auth Server -> Access Token -> Client -> Resource Server with Access token
- Access Token:
- JWT: [Link](subject: username).claims(claims: username?, exp. date?).sign(H256,
SECRET_KEY).build();
- How to extract user details from access token?
- Microservices communication?
- Exception at 1 Microservice: propagation?
Java
I. JIT Compiler
The JIT compiler is enabled by default, and is activated when a Java method is called. The JIT
compiler compiles the bytecode of that method into native machine code, compiling it "just in
time" to run. When a method has been compiled, the JVM calls the compiled code of that
method directly instead of interpreting it.
To help the JIT compiler analyze the method, its bytecode are first reformulated in an internal
representation called trees, which resembles machine code more closely than bytecode.
Analysis and optimizations are then performed on the trees of the method. At the end, the trees
are translated into native code.
Inlining is the process by which the trees of smaller methods are merged, or "inlined", into the
trees of their callers. (Method call is evaluated)
II. OOPS
- Encapsulation: protecting data using access modifiers: public private protected - data hiding
[For easily changing the Implementation for a setter/getter method later]
Solution:
1. Synchronized block: ensures atomic execution, as long as both threads are locked on the
same object (Consumer doesn't enter during (Producer's TOCTOU)
2. BlockingQueue: put() and take() implicitly check state of queue(empty/full)
- Pass a BlockingQueue object while creating Runnable object of Producer/Consumer class
- put() or take() in run method
V. JDBC
Connection conn = [Link](url, name, password)
[Link]()
[Link](sql)
CallableStatement cstmt = [Link](sql) : to execute stored procedure.
[Link]()
[Link](sql)
[Link](sql)
[Link](1,...) setString(...)
[Link]
VI. Variables
- Instance variables have initial default value (null or 0), local don't
- final variables don't ([Link]
A blank final instance variable must be definitely assigned at the end of every constructor of the
class in which it is declared; otherwise a compile-time error occurs
- for final variables, as long as value is assigned in constructor/init block, compiler does not
complain
- a final reference variable is immutable. Object it points to, may not be.
eg. final StringBuffer sb = new StringBuffer("a");
[Link]("b"); // works
sb = new ... // doesn't work
- static variables and their technical values (primitives or references) are stored in PermGen
space. Objects assigned to static references are stored in heap
2. Singleton:
- early: new object is created at class level
- late: init if null, else return inited object (un-init static ref at field level)
- double checked locking/enum: thread safe
- private constructor
- private Object to return
- reflection : use enum to prevent instantiation
- cloning : override clone() method and throw CloneNotSupportedException
3. Factory Pattern:
- Multiple classes implement the same interface
- [Link]() returns object with return type interface
- eg. [Link]() returns Type Map<>
4. Observer Pattern:
- Subject holds a list of Observers
- Whenever an Observer is instantiated, common object of Subject class is passed through
constructor
- Constructor in each Observer adds itself to Subject's list of observers by calling add method of
Subject object passed
- whenever state of Subject is changed (using setter method), the method iterates through list of
Observers it holds and performs actions
- [Link]
- Behavioral Patterns: this, visitor, template, etc.
6. Composite (S)
- used when type of object is not known and casting is required.
- common interface is implemented by all object types. casting is avoided by calling interface
method
- eg. in a hierarchy of files. objects are of type Directory or File. Both implement interface I
- [Link]
VIII. Classes, Methods and String
Inner class:
- Static nested classes can access only static members of the outer class.
- A static class object can be created with the following statement:
[Link] nestedObject = new [Link]();
- inner classes are associated with the instance, we can’t have any static variables in them.
- InnerClass innerClass = [Link] InnerClass();
- Note that inner classes can access outer class private members and at the same time we can
hide inner class from outer world.
- Immutable class: class, data members final (not static), private constructor, no setter methods,
only getter methods
String is immutable. Stored in string pool. Password should be stored in char array since, you
can set it to blank once you are done with it with confidence that it will no longer be retained in
memory.
Only using new(), etc will initialize the class (static or not)
Init triggers initialization of static blocks of Parent then Child, followed by non static blocks of
both
[Link] triggers initialization of Only Parent static block, not non static
[Link]():
PrintStream out is set to null using nullPrintStream() method since:
1. System has to be the first to be loaded and initialized not PrintStream [out]. Initializing out to
a value would cause PrintStream to be initialized.
2. out can't be explicitly assigned to null
if it was set to null, the compiler would consider it as a constant, and would replace all the
references to [Link] in other classes with null (that's what inlining means), since out is final
static.
3. nullPrintStream uses an if condition with current time in millis > 0, to bypass inlining
4. later set with initializeSystemClass(), which uses JNI native code to bypass restriction of not
being able to re initialize value of final static reference var [Link]
static keyword:
- Class loader initializes static var as part of class init (at runtime)
- static methods can access non static vars/methods only through instance. Hence, calling non
static method from static method requires object, but non static methods can call
- non static can access static, not vice versa w/o an object
- non static methods can access static via [Link]() or simply staticMethod(). same
with any non static target method
interface B extends A {
default void m() {
[Link]("hello from B");
}
}
interface C extends A {}
class D implements B, C {}
the code
C c = new D();
c.m();
- will print hello from B. The static type of c is unimportant; it is an instance of D, whose most
specific version of m is inherited from B.
- default methods are virtual (dynamic binding)
- private, final and static members (methods and variables) use static binding
Enum:
- first line in enum must be declarations
- can be used in switch statements
enum Color { RED } is implicitly:
class Color
{
public static final Color RED = new Color();
}
XI. Algorithms
BST: O(log2 n)
After Iteration 1,
Length of array = n/(2^1)
partition(arr, low, high) returns index of pivot after sorting such that elements <pivot are to the
left
recursive call to method(arr, low, pivot-1) and 2nd half
- start partition with i = low - 1; j = low and j < high
- in partition(), compare j with pivot and swap(i++)
- same arr reference is passed. hence print(arr) will be sorted
Insertion sort:
- start with j = 1, i = 0, hold key = a[j]
- if a[j] < a[i], move a[i+1] = a[i], j--
- keep swapping until not greater or j!=0
XII. Overriding
Exceptions
- If SuperClass does not declare an exception, then the SubClass can only declare unchecked
exceptions
- If SuperClass declares an exception, then the SubClass can only declare the child exceptions
of the exception declared by the SuperClass, but not any other exception.
- If SuperClass declares an exception, then the SubClass CAN declare Zero exceptions
[Link]
__________________
XVII. Regex:
(?:(?!lazy).)*
[Link]
XVIII. Why Do Local Variables Used in Lambdas Have to Be Final or Effectively Final?
[Link]
_______________
Edited:
March 9, 2020
May 13, 2021
May 23, 2021
June 9, 2021
July 3, 2022
Sep 30, 2022
Nov 24, 2022 (added String concat vs + NPE)
Threads
Threads: 9h
Instantiating, States:
- 3 ways:
1. MyThread extends Thread: since Thread class implements Runnable
2. ThreadRunnable implements Runnable, pass to new Thread(runnableObject): allows
multiple inheritance, preferred. Also, subclassing should be reserved for specialized versions of
more general superclasses.
3. Callable interface. call() instead of start. Cannot pass same as runnable. executorService =
[Link]()
- Future<String> future = [Link](callableObject)
- Callable call() method will return object of type String, which is stored into future object.
- [Link](), cancel() if not yet started, etc
- Set = Set Of Callables
Synchronization:
- Ensures that no other thread locked on the SAME runnable/thread object can access until
current thread completes Synchronized code
- Thread threadA = new Thread(new ThreadRunnable())
Thread threadB = new Thread(new ThreadRunnable())
threadA and threadB represent different Runnable instances
Using "synchronized(this)" anywhere in target class would then have lock on different
instances. threadB would interrupt threadA
- Also, calling synchronized method with new instance, would not lock on same instance.
eg. new ThreadRunnable().methodTest(), where methodTest() is a method in ThreadRunnable
class, and is called from within run() method, is synchronized.
calling new ThreadRunnable().methodTest() each time won't provide sync., since the sync is on
"this", which refers to different instances in this case.
synchronized static:
- Threads calling non-static synchronized methods in the same class will only block each other
if they're invoked using the same instance.
- static synchronized methods in the same class will always block each other—they all lock on
the same Class instance
- Two threads executing the same method at the same time will use different copies of the local
variables,
- a static synchronized method and a non-static synchronized method will not block each
other
- Access to static fields should be done from static synchronized methods. Access to
non-static fields should be done from non-static synchronized methods.
- volatile:
Read/write occur to main memory. Since 2 threads might update var in CPU cache and read old
value from main memory.
Guarantees this visibility. Values are read as updated.
Does not guarantee atomicity. eg. i++
Synchronized takes care of both
Semaphore:
- Class in Java concurrent pkg
- used to control how many threads can access critical section
- Semaphore(int) is passed to Thread monitor object constructor
- [Link]() decrements, release() increments the value
______________
2021:
Concurrent Pkg
- ReentrantLock // no sync keyword
- [Link](), unlock()
- BlockingQueue Eg.: [Link]
______________
Edited:
- Feb 3 2020
- Jun 9 2021
Exception Handling & Serialization
Exception Handling: 2h
- A try clause by itself will result in a compiler error. Any catch clauses must immediately
follow the try block. no line in between
- can catch more than one type of exception in a single catch clause. (pipe operator, order
matters)
- You can throw the exception out of main() as well. This results in the Java Virtual Machine
(JVM) halting, and the stack trace will be printed to the output. Same if not handled at all
- The handlers for the most specific exceptions must always be placed above those for more
general exceptions.
- If one Exception class is not a subtype or supertype of the other, then the order in which the
catch clauses are placed doesn't matter.
- Handle or Declare: Each method must either handle all checked exceptions by supplying a
catch clause or list each unhandled checked exception as a thrown exception.
- RuntimeException, Error, and all of their subtypes are unchecked exceptions and unchecked
exceptions do not have to be specified or handled
- Rethrowing the Same Exception: All other catch clauses associated with the same try are
ignored. if a finally block exists, it runs, and the exception is thrown back to the calling method
(the next method down the call stack). If you throw a checked exception from a catch clause,
you must also declare that exception!
- StackOverflow error: method stack overflows. eg. recursive call to same method
- AssertionError IS thrown programmatically
- finally() is always invoked, unless [Link]() is called, usually used to close resources
Serialization: 2.25h
- Steps:
- 1. Serialization I/O code in try/catch
- 2. ObjectOutputStream os = new ObjectOutputStream(fileOutputStream);
[Link](object);
[Link]();
- 3. ObjectInputStream ois = new ObjectInputStream(fis);
Cat object = (Cat) [Link]();
[Link]();
- [Link]: for composite objects that are not serializable
- transient variables/Object references will be skipped. the references will exist, but object state
won't be serialized. Object references marked transient will always be reset to null
- If composite class cannot be serialized, in class to be serialized:
- mark object reference transient
- private void writeObject(ObjectOutputStream os
{
try { [Link](); // normal ser.
[Link](anything); } }.
when [Link](object) is called readObject() method in target class is invoked.
([Link]
- When an instance of a serializable class is deserialized, the constructor does not run, and
instance variables are NOT given their initially assigned values!
- Think of constructors and instance variable assignments together as part of one complete
object initialization process (and in fact, they DO become one initialization method in the
bytecode).
- transient variable will be reset to 0.
transient Object reference will be reset to null
- If you are a serializable class, but your superclass is NOT serializable, then any instance
variables you INHERIT from that superclass will be reset to the values they were given during the
original construction of the object. This is because the nonserializable class constructor WILL
run!
- In a collection or an array, every element must be serializable!
Collections
- If two objects are defined as equals(), hashcode() method must be overriden. Since, if two
objects are logically equivalent their hashcode must be same
- If hashcode is the same, object will be assigned to same bucket, differentiated by object's key
- If key as well is same,(i.e exactly same Object), then replace the value
- comparing hashcode is cheaper than checking equality
-[Link]
xrsuwu00
1. Map<Key, Value> :
HashMap:
- Initial value is 16. hashbuckets are elements of array of Node<> which is linked list. (Tree
Java8)
- put() method returns old value for a key if exists, else null
- Key Object has hashcode() and equals() method
- i. If 2 Objects are equal, their hashcode() must be equal
ii. If 2 Objects are not equal, their hashcode() may or may not be equal
- If 2 keys have the same hashcode() value, hashMap uses linked Node to handle collision.
traverses Entry objects using [Link]()
- for an existing key value is overriden regardless of equality of value
- [Link]() returns Set<[Link]<K, V>>
- Sort by value:
- get a linked list from [Link]()
- [Link](): send a list and comparator object that compares two [Link]<>
values by [Link]().compareTo([Link]())
[Link]
TreeMap:
- TreeMap does not use hashCode() or equals() at all! It solely relies on the compareTo() method
and if your equals() does not comply with compareTo(), TreeMap does not care. it must
([Link]
[Link])
2. Queue
- poll(): return value/null,
remove(): return and remove/exception
- PriorityQueue keeps the lowest element as per Comparator or Comparable at head position
6. Hashtable vs ConcurrentHashMap
Hashtable synchronizes at method level on the entire object.
CHM uses bucket-level locking, locks only for write operations. Iteration is one thread at a time.
8. Set
- HashSet uses map internally:
- add(E e) -> return [Link](e, PRESENT) == null
- If returned PRESENT, add will return false, since put method returns existing value
- Set subset includes lower limit excludes upper limit object
- TreeSet is naturally ordered (alphabetically in case of Strings)
Set doesn't hold duplicates
Not necessarily ordered (insertion order), unless of course it's a LinkedSet
- Treeset uses map internally, uses equals as well as Comparable
- Adding element to sorted set: BST?
- Hashset POJO object by default uses reference address as hashcode, got equals
9. LinkedList<>
- uses an inner private class called Node
- Node constructor: Node<E> previous, data, Node<E> next
- The class stores the first and last Node<E> reference
- for add (to last) : temp node reference points to current last node on heap.
current [Link] node will point to newNode
last reference will point to newNode
push(T val) {
Node<T> newNode = new Node<T>();
[Link] = val;
[Link] = head; // newNode next will point to current head (head could be null if empty)
head = newNode; // update current head
}
T pop() {
if (head != null)
tempValue = [Link];
head = [Link]; // head ref var is now pointing to where [Link] was pointing
return tempValue;
}
}
Generics:
- Use T instead of ? when you need to relate parameters/return type
- ? makes code more readable
- T: Any type
?: Wildcard
- ? extends/super Type : Type bounded
Differences: (T can be used in scope, only extends, allows multiple bounds)
- T can be used elsewhere, ? cannot
- ? can have both lower and upper bounds, T can only have upper bounds (T extends Something)
- T can have multiple bounding classes(T extends Comparable<T> & Cloneable<T>)
[Link]
- PECS Rule:
[Link]
if method only reads a list of Parent objects, List<? extends Parent> should be used as the
method param. This allows us to pass both List<Child> and List<Parent> to the method
______________
Last Edited:
- March 11, 2020
- June 11, 2021 (Double Brace Init)
- March 10, 2023 (PECS Rule)
Java 7/8
Java 7:
1. Diamond “<>” Operator
2. Strings in switch Statement
3. Multi-catch similar exceptions, More precise exception rethrow
4. Automatic Resource Closing
5. Underscore in Numerical Literals
6. Binary Literals with Prefix “0b”
7. Fork-Join rethrow
______________________________________
Java 8:
1. Lambda Expressions
2. Functional Interfaces
3. Method References
4. Interface Default and Static Methods
5. Streams API
6. Optional
7. Date/Time New API
8. CompletableFuture<>
9. Type Inference
1. Lambda Expressions:
i. With Lambda Expression:
[Link](rosterAsArray,
(Person a, Person b) -> {
return [Link]().compareTo([Link]());
}
);
3. Method References:
[Link](rosterAsArray, Person::compareByAge);
. Reference to a constructor
ClassName::new
5. Streams API:
- [Link]().map(str -> [Link]()).forEach([Link]::println);
- [Link]()
.filter(t -> [Link]() == [Link])
.sorted(comparing(Transaction::getValue).reversed())
.map(Transaction::getId)
.collect(toList()); [Link]
6. Optional
Optional<String> op = [Link](str[2]);
[Link]() returns true if str[2] is not null
- Optional<Address> op = [Link]();
[Link]([Link]::println);
- [Link](), [Link]()
8. CompletableFuture<>:
- There's a lot, trust me
- It's better than Future<>:
runAsync(Runnable..) : executes in a new Thread
supplyAsync(Runnable..) : runs and returns value from new Thread
complete(): manually complete
perform further action on a Future’s result without blocking using a callback function
[Link]
___________________
Edited:
March 11, 2020
May 23, 2021
Spring, Hibernate
AbstractController:
- override handleRequestInternal method
ParameterizableViewController:
- getViewName() method sets view name via xml file (DI)
- return MAV(getViewName(), map)
UrlFilenameViewController:
- in dispatcher-servlet: UrlFilenameViewController's purpose is:
Transforms the virtual path of a URL into a view name and returns that view
eg. <bean name = "hello" class="UrlFileNameViewController">
<bean class = "SimpleUrlHandlerMapping"><property
name=mappings><value>/**/*.html</value></>
.. in web xml servlet url-pattern is "*.html"
MultiActionController:
- myController extends MAC
- actionName = controller method names
- do not override handleRequest and handleRequestInternal. handleRequestInternal redirects to
resp. methods
- SimpleURLHandlerMapping props name=mappings > <property
key=[Link]>Controller bean id</>
BaseCommandController
- maps from html:form using setter methods
[Link]
7. @RequestMapping("/path", params=...)
Overloading with params is possible
9. Autowiring modes:
eg. <bean id =... autowire = "byType"> OR @Component(...)
- byType : default
- if multiple beans exist with the same type, specify @Qualifier(name)
else - throws error
byType: Spring looks for a bean with the type expected by property or constructor arg(Employee
e: "Employee" is the type, "e" is the name)
@Primary annotation if autowired by type and >1 bean with same type
- @Primary only makes sense when we enable the component scan
- @Configuration
@ComponentScan(basePackages="[Link]")
public class Config { ... }
@Bean
public LocalSessionFactoryBean getSessionFactory()
else in XML:
<bean value="...LocalSessionFactoryBean">
<property name = "sessionFactory" >