> For the complete documentation index, see [llms.txt](https://ysfang82.gitbook.io/development-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ysfang82.gitbook.io/development-notes/programming-langauges/java/java-fundamentals.md).

# Java Fundamentals

**Memo**

* [Modifier Types](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
  * `private`
  * `default` (no modifier): within package
  * `protected`: within package and sub-classes
  * `public`
* Special modifier
  * `volatile`: variables wouldn't be cached by threads, must be read / write within main memory.
  * `transient`: variables would be excluded during serialization / deserialization.
* Enum&#x20;
  * Constants can be initialized with one or more attributes with different types.
    * Override `hashcode` / `equals` for hash collections and lambda grouping.
  * Constant `name` / `toString`, enum `valueOf` are mentioning the constant.

**Java 8 Features**

* Stream
  * Primitive Stream
    * Ex. `IntStream`
      * Method for iteration: `range`, `rangeClosed`
      * Using `mapToInt(Class::getter).toArray()` to assign to an `int[]`
      * Don't need to specify Comparator in `min()`, `max()`
  * Statistics method
    * Ex. `average()`
      * Using `orElse()` / `getAsDouble()` to set up a default value. (changing assignation from an `OptionalDouble` to a `double`)
    * `summaryStatistics()` encapsulates count, avg, sum, min, max.
  * `findFirst()` is deterministic, and `findAny()` is not.
  * Group By
    * One attribute
      * `.collect(Collectors.groupingBy(Class::getterMethod))`
    * Multiple attributes should be encapsulated into an tuple (DIY) object.
      * `.collect(Collectors.groupingBy(object -> new Tuple(object.getter1(), object.getter2(), ..)`
* [Optional](https://iter01.com/523393.html)
* [CompletableFuture](https://kknews.cc/zh-tw/code/ppqg86z.html)
  * For callee to invoke other operations.

**GC**

* Goals
  * Shorten full GC time
  * Let fewer instances to get into to old generation
* Memory composition
  * Shared by threads
    * Heap (shared by threads, storing: non-primitive objects, class members, static variables)
      * Young Generation
        * Composition (suggested ratio - 8:1:1)
          * Eden
          * From Survivor
          * To Survivor
        * When Eden is full, trigger Minor GC to copy survivors into **To Survivor**, and release Eden, **From Survivor**. If **To Survivor** is full, instances get into the Old Generation.
        * Adjusted with -Xmn: (or separately with: -XX:NewSize, -XX:MaxNewSize)
      * Old Generation
        * When Old Generation is full, trigger Full GC to utilize Old Generation.
        * Old Generation space is: -Xmx subtracts with -Xmn
      * Heap is adjusted with: -Xms, -Xmx
    * Permanent (or called "Method area")
      * Storing classes, methods, constant pool
      * Adjusted with: -XX:PermSize, -XX:MaxPermSize
  * Owned by a thread, in Code Cache (or called "Native area") for threads.
    * Program counter
    * Natives&#x20;
    * Stack (owned by each thread) to store:&#x20;
      * Methods being called&#x20;
      * Arguments being passed&#x20;
      * Local primitive type variables, local references
    * Adjusted with: -Xss
* Algorithms
  * mark and sweep (used in old generation of heap)
  * copying (used in young generation of heap)
  * mark and compact (used in old generation of heap)
* Collectors
  * Serial
    * single threaded, mark and sweep (Effective but long Stop The World time)
  * Parallel
    * multi-threaded, mark and sweep (High throughput but long STW time)
  * CMS
    * concurrent mark and sweep (low STW, but consumes CPU)
    * steps
      * CMS inital mark (STW)
      * CMS concurrent mark
      * CMS remark (STW)
      * CMS concurrent sweep
  * G1
    * for low latency scenarios (replacement for CMS, suggested to use on machine with HEAP space of 6G up)
    * dividing heap into regions (1\~32Mb)
* Tricks
  * To create a memory dump when the the OutOfMemory error occurs.
    * Add: `-XX:+HeapDumpOnOutOfMemoryError`
* Reference
  * [Thread states](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.State.html)
  * [Java 記憶體組成與參數、回收判斷、回收演算法](https://kknews.cc/zh-tw/tech/8gokx34.html)
  * [GC Collector差異與概念作法](https://kknews.cc/zh-tw/code/r56glvr.html)
  * [如何优化Java GC](https://crowhawk.github.io/2017/08/21/jvm_4/)
  * [JVM 的内存管理与 GC 调优](https://zhuanlan.zhihu.com/p/54051496)
  * [Types of OutOfMemoryError](https://javarevisited.blogspot.com/2011/09/javalangoutofmemoryerror-permgen-space.html#targetText=OutOfMemoryError%20in%20Java%20is%20a,heap%20to%20allocate%20that%20object.)
  * [Tricks of the Trade: Tuning JVM Memory for Large-scale Services](https://eng.uber.com/jvm-tuning-garbage-collection/)
