Java
In this guide, we introduce some knowledge about Java.
General
- Java compilation:
.java,.classand binary files- Hotspot, JIT, AoT (ahead of time) compilation
- Difference between Java and C++:
- Memory management
- Multi-inheritance
- Difference between override and overload
- Difference between
StringBuilderandStringBuffer:- Both extend the abstract class
AbstractStringBuilder StringBufferis thread-safeStringBuilderis not thread-safe, but is about 10% better in performance
- Both extend the abstract class
- Difference between abstract class and interface:
- Interface only allows public methods, while methods in abstract class allow all different access modifiers
- Abstract methods in an abstract class cannot be
private, though. Otherwise, subclasses cannot see and implement it
- Abstract methods in an abstract class cannot be
- Methods in interface cannot have implementation, while non-abstract methods in abstract class can
- Starting from Java 8, interface can declare a method as
defaultand have implementation
- Starting from Java 8, interface can declare a method as
- Fields in interface must be
public static final, while there is no restriction for fields in an abstract class - A class can implement multiple interfaces, but can only extend one abstract class
- Interface only allows public methods, while methods in abstract class allow all different access modifiers
- Difference between
final,finallyandfinalize:finalis used to declare a class that cannot be inherited, a method that cannot be overridden, or a field whose value cannot be changedfinallyis a block of code that will always be executed no mattertryorcatch- Code in
finallywill only be skipped if the program, the process or JVM crashes - If both
tryandfinallyreturn a value, the actual return value will be the one fromfinally
- Code in
finalizeis the method being called by GC before a class is garbage-collected
- Difference between
==,equalsandhashCode:==is used to compare the memory addresses of two objectsequalsis used to compare equality, and will fall back to==if it is not overridden in the classhashCodeis used to compute hash value of an object, and will be used in collection framework such asHashMap- If
equalsreturntrue,hashCodemust return the same value; but not vice versa
- Difference between
Throwable,Error,Exception,RuntimeExceptionandassert:Throwableis the most generic class fromjava.langpackageErrorinherits fromThrowableand represents serious errors that are usually not recoverable. You can but should NOT catchErrorsExceptionalso inherits fromThrowable. There are two types of exceptions, checked and un-checked exceptions. An exception becomes an un-checked exception when it inherits fromRuntimeException, a subclass ofException. Any checked exception must be catched or declared in method signature usingthrows.assertis used to verify the correctness of an invariant in the code. They should not be used in production environment. To enable assertion in Java, pass an-eacommand to JVM.
- Difference between
BIO,NIOandAIO:BIOis the most traditional mode, which stands for blocking I/O.NIOstands for new, non-blocking I/O, which is introduced in Java 4. It supports channel and buffer.AIOis the 2nd generation ofNIO, which is introduced in Java 7. It supports an asynchronous, non-blocking model, similar to JavaScript.
Collection Framework
- Difference between
LinkedList,ArrayListandVector:Vectoris thread-safe, whileLinkedListandArrayListare not.- However, this also means
Vectorcould bring performance bottleneck. - The OpenJDK is working torwards a compile-time solution to optimize
Vectorby using the optimal vector hardware instructions on CPU. See JEP 338.
- However, this also means
LinkedListdoes not support random index access, whileArrayListandVectordo.ArrayListis a dynamic array. Thus, it supports automatic capacity growth:ArrayListhas a default capacity of 10.- Starting from Java 7,
ArrayListsupports deferred default capacity. When created, theArrayListis empty. It will only have a capacity of 10 when first insertion happens.
- Starting from Java 7,
ArrayListgrows at the rate of 1.5:- This is calculated by
oldCapacity + (oldCapacity >> 1). Java 7 uses bit operation to improve performance. - To copy old elements over to the new array,
Arrays.copyOfis used.
- This is calculated by
- Difference between
Hashtable,HashMap,ConcurrentHashMap,LinkedHashMap,TreeMapandIdentityHashMap:- The key for
HashMapmust implement bothequals()andhashCode(). HashtableandConcurrentHashMapis thread-safe, butHashMapis not.- However,
ConcurrentHashMapwould provide better performance under high concurrency.
- However,
HashMapis implemented as an array ofLinkedLists (because of hash conflict):- Starting from Java 8, the underlying
LinkedListwill be changed to a red-black tree when there are more than 8 items in the bucket. It will be converted back to aLinkedListwhen there are less than 6 items in the bucket.
- Starting from Java 8, the underlying
HashMaphas an initial size of 16 and a default load factor of 0.75:- When exceeding the current capacity, the
HashMapwill resize with a factor of 2. This is calculated byoldCap << 1.
- When exceeding the current capacity, the
Hashtablehas an initial size of 11 and a default load factor of 0.75- When exceeding the current capacity, the
Hashtablewill resize with a factor of about 2. This is calculated by(oldCap << 1) + 1.
- When exceeding the current capacity, the
ConcurrentHashMapuses segments to have better concurrency support. Theoretically, the number of concurrent access allowed is equal to the number of segments.- By default,
ConcurrentHashMapcreates 16 segments. - Starting from Java 8,
ConcurrentHashMapis re-designed. It uses an array ofLinkedLists (or red-black trees when there are too many items in a bucket). Effectively, it is the same asHashMap. It uses CAS to add lock when necessary.
- By default,
LinkedHashMapis similar toHashMap, but it preserves the insertion & access order of the elements inside. It is a subclass ofHashMap, and is introduced in Java 4.- However, similar to
HashMap,LinkedHashMapis not thread-safe. - Internally,
LinkedHashMapmaintains a double linked list. Whenever a new element is inserted or an old element is accessed, that node will be put to the head of the double linked list. LinkedHashMapis useful for implementing an LRU (least recently used) cache.
- However, similar to
TreeMapis also a key-pair collection. Although it supports ordering, its access time complexity isO(logn)rather thanO(1).- Internally, a balanced red-black tree is maintained.
IdentityHashMapuses reference-equality rather than object-equality when comparing keys. Its original use case is to store topology-preserving graph transformation, such as serialization or deep copying. However, it can actually be used as aMultiHashMap, in which we can store multiple entries with equal keys.
- The key for
Concurrency
- Difference betwen co-routine, thread and process:
- Java supports multi-process and multi-thread only.
- Thread is a lighter concept compared to process. Threads from the same process share some common resources, so we could save some resources when doing context switches between threads.
- Difference between
RunnableandThread:- Both are used to implement multi-thread in Java. Both need to override the
runmethod. Runnableis an interface, whileThreadis a class.Threadactually also implements theRunnableinterface.- Since Java does not support multi-inheritance, it may be better to use
Runnableto support more features. - Also, using
Runnablecan help to share resources (i.e., you can instantiate oneRunnableobject and use multipleThreadobjects to start with it. Then, the fields inside thatRunnableobject will be shared).
- Both are used to implement multi-thread in Java. Both need to override the
- Different use cases of
synchronized:- Lock for the whole class when using it on static methods.
- Lock for the single instance otherwise.
- Lock expansion process:
- No lock: initial state
- Bias lock: single-threaded competition
- Lightweight lock: multi-threaded competition, but only one thread can compete at any time
- Heavyweight lock: multi-threaded competition at the same time
Spring
- IoC (inverse of control), DI (dependency injection), AOP (aspect-oriented programming)
- Spring AOP separates the business logic and system services (such as logging, auditing, transaction management). It in fact uses the delegate pattern. In oher words, it attempts to use either
XMLconfiguration files or Java annotations to dynamically and implicitly insert the code for system services into the code for business logic. - IoC is a useful design pattern. In Spring, all objects will be stored in IoC containers. These containers then adopt the factory pattern and provides the instantiation of objects when needed. Therefore, there is no need to manually create these objects.
- DI can be achieved via either constructor or setter.
- Spring AOP separates the business logic and system services (such as logging, auditing, transaction management). It in fact uses the delegate pattern. In oher words, it attempts to use either