Prepare for 2022 spring move - java-day8

java

  1. What are strong reference, soft reference, weak reference and virtual reference?
    • Strong reference (default support mode): when the memory is insufficient, the JVM starts garbage collection. For strongly referenced objects, even if there is OOM, the object will not be recycled and will not be collected.
    • Soft reference: when the system memory is sufficient, the object will not be recycled; When the system runs out of memory, objects are recycled. (application scenario: read a large number of local pictures. If the pictures are read from the hard disk every time, it will seriously affect the performance; if they are loaded into memory at one time, it may cause memory overflow)
    • Weak reference: whenever gc occurs, it will be recycled.
    • Virtual reference: it can be collected by the garbage collector at any time.
  2. If you know weak references, can you talk about WeakHashMap?
    WeakHashMap, which can realize self-cleaning. That is, the unused key data in the map is automatically cleaned up and the used key data is still kept.
    public class WeakHashMapDemo {
        public static void main(String[] args) {
            myHashMap();
            System.out.println("==================");
            myWeakHashMap();
        }
    
        private static void myWeakHashMap() {
            Map<Integer, String> map = new WeakHashMap<>();
            Integer key = new Integer(2);
            String value = "WeakHashMap";
    
            map.put(key, value);
            System.out.println(map);
    
            key = null;
            System.out.println(map);
    
            System.gc();
            System.out.println(map + "\t" + map.size());
        }
    
        private static void myHashMap() {
            Map<Integer, String> map = new HashMap<>();
            Integer key = new Integer(1);
            String value = "HashMap";
    
            map.put(key, value);
            System.out.println(map);
    
            key = null;
            System.out.println(map);
    
            System.gc();
            System.out.println(map + "\t" + map.size());
        }
    }
    
    Operation results:
  3. ReferenceQueue: reference queue?
    Reference Queue. After detecting the appropriate reachability change, the garbage collector adds the registered reference object to the Queue to realize the enqueue and dequeue (poll and remove) operations of a Queue. The internal element is a generic reference, and the implementation of the Queue is realized by the reference's own linked list structure (one-way circular linked list). (post notification in reference)
  4. OOM?
    • StackOverflowError: stack overflow. The application runs out of stacks due to deep recursion. Whenever a java program starts a new thread, the Java virtual opportunity allocates a stack to it, and the Java stack maintains the running state of the thread in frames; When a thread calls a method, the jvm pushes a new stack frame into the thread's stack. As long as the method has not returned, the stack frame will exist. If the method has too many nested call levels (such as recursive calls), with the increase of frames in the Java stack, the total size of all stack frames in the thread's stack will eventually be greater than the value set by - Xss, resulting in StackOverflowError overflow exception.
    public class StackOverflowErrorDemo {
        public static void main(String[] args) {
            stackOverflowError();
        }
    
        private static void stackOverflowError() {
            stackOverflowError();
        }
    }
    
    1. OutOfMemoryError:Java Heap Space. Heap overflow
    public class JavaHeapSpaceDemo {
         public static void main(String[] args) {
             byte[] bytes = new byte[80 * 1024 * 1024];
         }
     }
    
    1. OutOfMemoryError:GC overhead limit exceeded. The JVM spends 98% of its time on garbage collection, but only gets 2% of the available memory. If the memory is recycled frequently (at least five consecutive garbage collections have been performed), the JVM will expose Java Lang. outofmemoryerror: GC overhead limit exceeded error.
    2. OutOfMemoryError:Direct buffer memory. Direct memory overflow.
    3. OutOfMemoryError:unable to create new native thread. Reason: ① the system memory is exhausted and unable to allocate memory for new threads; ② The number of threads created exceeds the limit of the operating system. Solution: ① check whether the application has created too many threads; ② Adjust the threshold of operating system threads; ③ Increase machine memory; ④ Reduce heap memory; ⑤ Reduce the number of processes; ⑥ Reduce the thread stack size.
    4. OutOfMemoryError:Metaspace. Meta space overflow.

algorithm

Given a positive integer n, generate one containing 1 to n 2 n^2 n2 is a square matrix in which all elements are spirally arranged in clockwise order.

Example:

Input: 3 output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]
Simulate the process of drawing the matrix clockwise:
-Fill up from left to right
-Fill the right column from top to bottom
-Fill down from right to left
-Fill left column from bottom to top
When we draw a circle here, we should draw every four edges. How to draw these four edges? Each edge should adhere to the consistent principle of left closing and right opening, or left opening and closing, so that this circle can be drawn according to the unified rules.

public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        // Number of cycles
        int loop = n / 2;

        // Middle position
        int mid = n / 2;
        // Define offset
        int offset = 1;

        // Define the initial position of each cycle
        int startX = 0;
        int startY = 0;

        // Fill number
        int count = 1;
        while (loop > 0) {
            int i = startX;
            int j = startY;

            // Upper filling
            for (; j < startY + n - offset; j++) {
                res[startX][j] = count++;
            }

            // Right fill
            for (; i < startX + n - offset; i++) {
                res[i][j] = count++;
            }

            // Lower filling
            for (; j > startY; j--) {
                res[i][j] = count++;
            }

            // Left fill
            for (; i > startX; i--) {
                res[i][j] = count++;
            }

            loop--;
            startX += 1;
            startY += 1;
            offset += 2;
        }

        if (n % 2 == 1) {
            res[mid][mid] = count;
        }

        return res;
  }

Keywords: Java Back-end

Added by ixos on Sat, 12 Feb 2022 08:03:20 +0200