This article is an Android interview questions, combined with the bottom right corner of the directory to eat better, including:

  • thread
  • Key in the thread
  • The thread pool
  • Utility classes in multithreading
  • process
  • Class loading
  • Patterns and reflections

thread


1. What are threads

Thread is the smallest unit that the operating system can dispatch. It is contained in the process and is the actual operating unit in the process. It can be used to speed up the operation of multithreading.

2. Several ways to write multithreading

  1. One is to inherit the Thread class.
  2. The other is to implement the Runnable interface. Either way, you override the run() method to define the behavior of a Thread. The latter is recommended because Java inheritance is single-inheritance. A class has a parent class, and if it inherits Thread, it cannot inherit other classes.
  3. Implement the Callable interface, in which the Call method produces a return value at the end of thread execution

3. What is a FutureTask

FutureTask implements the Future and Runnable interfaces to cancel tasks and retrieve return values.

4. How do I force a thread to start

No, like gc, only notifies the system, which controls when to start

5. Whether to enable a thread to call the run() or start() method

Starting a thread is a call to the start() method that puts the virtual processor it represents in a runnable state. This means that it can be scheduled and executed by the JVM. This does not mean that the thread will run immediately

6. Name thread scheduling and thread synchronization methods

Thread scheduling

  1. Wait ():Object method, which must be used in synchronized code blocks or synchronized methods to make the current thread wait and release the lock
  2. The notify ():Object method, used in conjunction with the wait method, notifies a thread. The JVM decides which thread to notify
  3. NotifyAll (): The Object method, used in conjunction with the wait method, notifies all threads, and the JVM determines which thread gets the right to run
  4. Sleep (): Puts a running thread to sleep, and is a static method called to handle InterruptedException

7. Synchronize threads

  1. Synchronized modification method
  2. Synchronized modifies code blocks
  3. Lock/ReadWriteLock
  4. ThreadLocal: Each thread has a copy of a local variable that does not interfere with each other. A way of exchanging space for time
  5. In Java has a lot of thread safe container and method, can help us achieve thread synchronization: such as Collections. SynchronizedList () method will List to thread synchronization; Thread synchronization of hashMap with ConurrentHashMap. BlockingQueue blocking queues are also thread synchronous and are ideal for the producer-consumer pattern
  6. Extension: volatile (volatile variables are not cached in registers, but are read from main memory each time they are used) : visibility is guaranteed, atomicity is not guaranteed, and therefore not thread-safe. Used in a write multiread/status flag scenario

8. What is a reentrant lock

The so-called re-entrant lock refers to the unit of thread. When one thread acquires the object lock, the thread can acquire the lock on the object again, while other threads cannot

9. How to stop a thread in Java

  1. Java provides a rich API but not one for stopping threads
  2. Volatile booleans can be used to exit the loop of the run() method or to abort the thread by canceling the task

10. What happens when an exception occurs while a thread is running

  1. The thread will stop execution if the exception is not caught
  2. This exception can be caught with UncaughtExceptionHandler

11. Multiple threads share data

  1. Use the same Runnable object
  2. Pass the same shared data instance to different Runnable objects using different runnable objects
  3. Use different Runnable objects as an inner class with shared data as member variables

Best practices/good habits for multithreading

  1. Give the thread a meaningful name
  2. Avoid locks and narrow down the scope of locks
  3. Use more synchronization helper classes (CountDownLatch, CyclicBarrier, Semaphore) and less wait and notify
  4. Use more concurrent collections and less synchronous collections

13. Design concept and function of ThreadLocal

  1. A local variable within a thread that is unique to the thread and not shared with other threads
  2. Application scenario: In multi-threaded scenarios, a variable does not need to be shared among threads. Each thread needs to be independent of each other

14. ThreadLocal principleWhat should I pay attention to when using

  1. ThreadLocal accesses data by retrieving the ThreadLocalMap inside the Thread instance
  2. The ThreadLocal instance itself serves as the key value
  3. If thread pools are used, Threadlocal might be the value of the previous thread and require the control we display
  4. ThreadLocal keys are weak references, but can still cause memory leaks (key null, value, and value) Android’s ThreadLocal implementation is slightly different, using the ThreadLocal instance as an array to store values, and using the ThreadLocal instance to compute a unique hash to determine the subscript.

15. Basic thread states and relationships between states

16. What happens if a thread within a synchronized block throws an exception

  1. Exceptions within a thread can be caught, and if not, the thread stops running and exits
  2. The lock in the synchronized block is released whether it exits normally or abnormally

17. What is a deadlock?

Two threads are waiting for each other to release resources before they can continue, creating a deadlock in which no one can continue (or multiple threads are waiting in a loop).

18. How to avoid deadlocks when N threads access N resources

Locks are locked and released in the same order

19. Why should wait conditions be checked in loops

Threads in the wait state may receive error alerts and pseudo-awakenings, and if the wait condition is not checked in the loop, the program will exit without meeting the end condition

20. What is the difference between synchronous and concurrent collections in Java

  1. Both synchronous and concurrent collections provide suitable thread-safe collections for multithreading and concurrency
  2. Concurrent collections have higher performance

21. What is the difference between live locks and deadlocks in Java

A live lock is similar to a deadlock, except that the state of the thread or process in a live lock is constantly changing. A live lock can be considered a special kind of hunger. A realistic example of a live lock is when two people encounter each other in a narrow hallway. Both people try to avoid each other so that they can pass each other, but because they avoid each other in the same direction, no one can get through the hallway. In short, the main difference between a live lock and a deadlock is that the state of the former process can change but execution cannot continue

22. How do I check if a thread has a lock

Java.lang.Thread has a method called holdsLock(), which returns true if and only if the current Thread has a lock on a specific object

23. What is the concurrency of ConcurrentHashMap in Java

ConcurrentHashMap Divides the actual map into parts to achieve scalability and thread-safety. This partition is obtained using concurrency, which is an optional argument to the ConcurrentHashMap class constructor and defaults to 16 to avoid contention in multithreaded cases

24. What are blocking methods

A blocking method means that the program waits for the method to complete and does nothing else. The ServerSocket Accept () method waits for the client to connect. In this case, blocking means that the current thread is suspended until the result of the call is returned and will not return until the result is returned. In addition, there are asynchronous and non-blocking methods that return before the task is complete.

25. What are busy loops in multithreading

A busy loop is one in which a programmer uses a loop to make a thread wait. Unlike the traditional methods wait(), sleep(), or yield(), which give up CPU control, a busy loop does not give up CPU. It simply runs an empty loop. The purpose of this is to preserve the CPU cache. In multi-core systems, a waiting thread may be running in another kernel when it wakes up, which will rebuild the cache. It can be used to avoid rebuilding the cache and reduce waiting time for rebuilding.

26. How to ensure that i++ results in multiple threads are correct

You can use synchronized to guarantee atomicity, or you can use the AtomicInteger class extension: Volatile only guarantees visibility, not atomicity, so no

27. Briefly describe the granularity of locks available in Java

Classes, objects, methods, or blocks of code can be locked in Java

A comparison between synchronized methods and synchronized code blocks

  1. Synchronous code blocks can specify smaller granularity
  2. A block of synchronized code can lock a specified instance

28. Class and object locks

Class lock A special object lock that locks the class object corresponding to the real time class

Keywords and classes in threads


0. Comparison of sleep and Wait methods

  1. Both methods suspend the thread and free CPU resources to other threads
  2. Sleep is the static method of Thread, and wait is the method of Object.
  3. Sleep blocks the thread; Wait causes a thread to enter the wait state, which is changed by notify or notifyAll of other threads
  4. Sleep can be used anywhere, and exceptions must be caught; Wait must be used in synchronized methods or synchronized blocks, or a runtime exception will be thrown
  5. Most important: sleep continues to hold the lock, wait releases the lock extension: yield stops the current thread, allowing the same or higher priority to execute first (but does not release the lock); The JOIN method calls another thread during the execution of one thread, and continues the execution of the current thread after the execution of the called thread finishes

1. What is the difference between a thread’s sleep() method and its yield() method

  1. The sleep method causes the current thread to block for a specified time and then enter the ready state
  2. The yield method puts the current thread into the ready state, allowing the same priority or higher priority to execute first
  3. The sleep method throws interruptedException

2. Why do wait, notify, and notifyAll not belong to Thread

JAVA provides locks at the object level rather than the thread level. Each object has a lock, which is acquired by the thread. It makes sense to call wait() on an object if the thread needs to wait for some lock. If the wait() method is defined in the Thread class, it is not obvious which lock the Thread is waiting on

3. Why are wait and notify called in synchronous blocks

  1. Java specifies that it must be in a synchronized block; exceptions will be thrown if it is not
  2. If notify is not in a synchronized block, wait may not receive a deadlock when it executes

4. Synchronized

Synchronized is used for thread synchronization

  1. Methods can be decorated
  2. Code blocks can be decorated
  3. When the lock is held by a class, all instance objects that call the method or block of code are locked

5. Differences between synchronized and ordinary methods

  1. When synchronized modifies static methods, the lock is a class, and all object instances use the same lock
  2. When decorating ordinary methods, locks are instances of classes

6. After A thread enters the synchronized method A of an object, can other threads enter the synchronized method B of the object?

Can’t. Other threads can access only asynchronous methods of the object. The first thread holds the object lock, and the synchronization method of the second thread also needs the object lock to run, so it has to wait in the lock pool.

7. What is volatile in Java

  1. Volatile is a modifier that can only modify member variables
  2. Volatile ensures visibility of variables (changes made by thread A are immediately available to thread B)
  3. Volatile disallows instruction reordering

8. Write a double-checked singleton

private static volatile Singleton instance;  

private Singleton(){}  
    
public Singleton getInstance(
if(singleton == null){
  synchronized(Singleton.class){
  if(singleton == null){ singleton = new Singleton(); }}}return sinlgeton;
)
Copy the code

9. Should the singleton’s private variables be volatile in DCL modeWhat is the use of this keyword

  1. To add
  2. If two threads access double lock at the same time, it is possible to reorder the instructions. Thread 1 initializes half and switches to thread 2. Since initialization is not an atomic operation, thread 2 does not read null directly, but crashes because initialization is not complete

10. Difference between Synchronized and Lock\ReadWriteLock

  1. Synchronized Java keyword, Lock/ReadWriteLock interface, they are reentrant Lock
  2. Synchronized is controlled by a VM and does not require users to manually release the lock. But Lock is the user display control, the user to manually release the Lock, if not actively release the Lock, it may lead to deadlock phenomenon.
  3. More methods of Lock can be used, such as tryLock () to get the Lock and return true, otherwise false; The tryLock(long time, TimeUnit Unit) method is similar to the tryLock() method except that it waits a certain amount of time before the lock is retrieved; Lock has the lockInterruptibly () method, which is an interruptible Lock
  4. ReentrantLock can implement fair locking (wait long to execute first)
  5. ReadWriteLock is an interface. ReentrantReadWriteLock is an implementation of ReadWriteLock. It divides access to a resource (such as a file) into two locks, a read lock and a write lock, improving read and write efficiency.

11. LockSupport

LockSupport is a lower-level class in the JDK that creates the basic thread-blocking primitive for locks and other synchronization utility classes

The Park method gets permission. Permissions are occupied by default and cannot be obtained when park() is called, so the unpark method is blocked to issue permissions

12. ReadWriteLock

  1. Read/write separation of locks to improve efficiency
  2. Reading can coexist, but writing and writing cannot

13. Implementation principle of Reentrant lock

  1. RetrantLock is implemented through CAS and AQS
  2. CAS (Compare And Swap) : three arguments, one current memory value V, the old expected value A, And the value B to be updated. Change the memory value to B And return true if And only if the expected value A And the memory value V are the same. Otherwise, do nothing And return false. Atomic operation
  3. RetrantLock inside a AbstractQueuedSynchronizer instance, AbstractQueuedSynchronizer is an abstract class, there are two in RetrantLock he implementation, is a fair lock, is a fair lock
  4. At lock time, call a CAS method called compareAndSet to set state, which is a volitale variable, to 1 and bind the current thread to the lock
  5. When compareAndSet fails, attempt to acquire the lock: state+1 if the thread bound to the lock is the current thread
  6. If the lock fails to be acquired, it is queued to wait, ensuring that concurrent operations become serial
  7. Extension: The difference between a fair lock and an unfair lock: the unfair lock ignores the queue and directly checks whether the current lock is available. A fair lock looks at the queue first and joins the queue if it is not empty

14. Others

The realization principle of synchronized and lock optimization? : How is Monitor Volatile implemented? Memory barrier CAS? What are the defects of CAS and how to solve them? AQS CompareAndSwap, by CPU instructions: AbstractQueueSynchronizer, is already an inner class how to detect a deadlock? How do I prevent deadlocks? : A deadlock must satisfy four conditions, and breaking any of them can unlock the deadlock Fork/Join framework

The thread pool


What is a thread pool?

  1. The frequent creation and destruction of objects is expensive, so Java introduced thread pools. The Executor interface in Java 5+ defines a tool for executing threads. Its subtype, the thread pool interface, is ExecutorService.
  2. Executors is a tool class that allows you to generate thread pools for certain features
NewSingleThreadExecutor: Creates a single threaded Executor that ensures that all tasks are executed in the specified order (FIFO, LIFO, priority). NewFixedThreadPool: Creates a thread pool that specifies the number of worker threads. Each time a task is submitted, a worker thread is created, and if the number of worker threads reaches the initial maximum of the thread pool, the submitted task is deposited to the pool queue. NewCachedThreadPool: Create a cacheable thread pool. If the length of the thread pool exceeds the processing requirement, free threads can be recycled. If none are recycled, new threads can be created. NewScheduleThreadPool: Creates a thread pool of fixed length and supports scheduled and periodic task execution.Copy the code
  1. ThreadPoolExecutor implements the ExecutorService interface. Here are the principles and parameters
If the number of threads in the CorePool is smaller than the size of the CorePoolSize thread, the new thread will execute the task. Step2. If the current thread in CorePool is greater than or equal to CorePoolSize, add the thread to BlockingQueue. Step3. If you cannot join BlockingQueue, create a thread to execute the task if it is smaller than MaxPoolSize. Step4. If the number of threads is greater than or equal to MaxPoolSize, execute the reject policy. Parameter Description:  ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) corePoolSize Size of the core thread pool maximumPoolSize Maximum capacity of the thread pool keepAliveTime When the thread pool is idle TimeUnit TimeUnit ThreadFactory ThreadFactory BlockingQueue task queue RejectedExecutionHandler thread rejection policy extension: The Submit and Excute methods of ThreadPoolExecutor both perform tasks. What's the difference? Submit accepts Runnable and Callable. 2. Submit returns a value. In exception handling, Submit can catch thrown exceptions through Future.getCopy the code

1. How to tune the thread pool and determine the maximum number

  1. The tuning of thread pools depends on the actual situation to maximize the utilization of system resources
  2. For example, if CPU efficiency is significantly higher than I/O, you should create more threads to improve CPU utilization and avoid I/O waits (see 1, see 2).
  3. The maximum number of cpus on Android can be: number of cpus *2+1, but it also depends on the situation, for example picaso will adjust the maximum number based on network conditions (see)

2. What happens if the thread pool queue is full when you submit the ThreadPoolExcuter task

2. If the number of threads reaches the maximum, submit the request to RejectExecutionHandler. 3. If no custom RejectExecutionHandler is configured, reject RejectExecutionExcuption

3. Usage and advantages of thread pools

Advantages: realize the reuse of threads, avoid the overhead of repeatedly creating and destroying threads; Using thread pools to manage threads uniformly reduces the number of concurrent threads, which often wastes too much time on thread context switching and thread synchronization.

Usage: We can create a thread pool ourselves by calling one of the constructors of ThreadPoolExecutor. But usually we can create a thread pool object more easily by using the Static factory method provided by the Executors class. Once the thread pool object is created, we can call the Submit or Excute methods to submit tasks for execution in the thread pool. When the thread pool is finished, remember to call shutdown to shut it down.

Utility classes in multithreading


0. Java concurrent programming:CountDownLatch, CyclicBarrier, and Semaphore

  1. CountDownLatch: You can use it for counter like functions. For example, if task A is waiting for the other four tasks to complete, CountDownLatch can be used to implement this feature
public class Test {
     public static void main(String[] args) {   
         final CountDownLatch latch = new CountDownLatch(2);
          
         new Thread(){
             public void run() {
                 try {
                     System.out.println(Child thread+Thread.currentThread().getName()+"In process");
                    Thread.sleep(3000);
                    System.out.println(Child thread+Thread.currentThread().getName()+"Executed"); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); }}; }.start(); newThread(){
             public void run() {
                 try {
                     System.out.println(Child thread+Thread.currentThread().getName()+"In process");
                     Thread.sleep(3000);
                     System.out.println(Child thread+Thread.currentThread().getName()+"Executed"); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); }}; }.start(); try { System.out.println("Wait for 2 child threads to complete...");
            latch.await();
            System.out.println("2 child threads have completed execution");
            System.out.println("Continue executing the main thread"); } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code
  1. CyclicBarrier: Implementation that makes a group of threads wait until a certain state before they all execute simultaneously
public class Test {
    public static void main(String[] args) {
        int N = 4;
        CyclicBarrier barrier  = new CyclicBarrier(N);
        for(int i=0; i<N; i++) new Writer(barrier).start(); } static class Writer extends Thread{ private CyclicBarrier cyclicBarrier; public Writer(CyclicBarrier cyclicBarrier) { this.cyclicBarrier = cyclicBarrier; } @Override public voidrun() {
            System.out.println("Thread"+Thread.currentThread().getName()+"Writing data..."); try { Thread.sleep(5000); System.out.println(system.out.println ("Thread"+Thread.currentThread().getName()+"Write data complete, wait for other threads to write data complete.");
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }catch(BrokenBarrierException e){
                e.printStackTrace();
            }
            System.out.println("All threads write, continue processing other tasks..."); }}} extension (CyclicBarrier and CountdownLatch) : 1.CountdownLatch waits for several tasks to complete and the CyclicBarrier waits for a state to be reached. CyclicBarrier can be reset. 3. Cyclicbarriers can have Runnable constructors that perform a task when a state is reached.Copy the code
  1. Semaphore: Semaphore controls the number of threads accessing a resource at the same time
public class Test { public static void main(String[] args) { int N = 8; Semaphore Semaphore = new Semaphore(5); // Number of machinesfor(int i=0; i<N; i++) new Worker(i,semaphore).start(); } static class Worker extends Thread{ private int num; private Semaphore semaphore; public Worker(int num,Semaphore semaphore){ this.num = num; this.semaphore = semaphore; } @Override public voidrun() {
            try {
                semaphore.acquire();
                System.out.println("Workers"+this.num+"Occupy a machine in production...");
                Thread.sleep(2000);
                System.out.println("Workers"+this.num+"Unleash the machine."); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); }}}}Copy the code

1. Semaphore in Java

  1. Semaphore can control the number of threads that are currently accessing resources. When the maximum number of threads is exceeded, the threads are blocked and wait
  2. When the number of threads is specified as 1, it can be used as a lock

2. How do all threads wait for an event to happen before they execute it

All threads need to block and wait, and automatic execution is observed when the event state change meets the condition, which can be implemented in the following way

  1. CountDownLatch: A lock is a typical synchronization utility class that waits for an event to happen. With the initial value of the lock set to 1, all threads call the await method to wait, and countDown is called when the event occurs to reduce the lock value to 0, and all threads waiting for the await latch can continue.
  2. BlockingQueue: all threads waiting for an event attempt to obtain an element from an empty BlockingQueue. Block. When the event occurs, add N elements to the BlockingQueue (N equals the number of waiting threads).
  3. Semaphore: Set the initial value of the Semaphore to the number of threads waiting N. At the beginning, the Semaphore application is completed and the remaining Semaphore is 0. When the event occurs, N occupied Semaphore is released at the same time, then all threads waiting for the Semaphore will acquire the Semaphore and continue to execute.

3. Producer-consumer implementationBlocking queue

  1. Extended: implemented with the sychronized keyword
  2. The characteristic of a blocking queue is that when the fetch or drop element is, the queue does not meet the condition (such as fetching when the queue is empty) and can block until the condition is met
public class BlockingQueueTest {
 private int size = 20;
 private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(size); 
 public static void main(String[] args) { 
 BlockingQueueTest test = new BlockingQueueTest();
 Producer producer = test.new Producer();
 Consumer consumer = test.new Consumer(); 
 producer.start();
 consumer.start(); 
 }
 class Consumer extends Thread{ 
 @Override public void run() {
 while(trueQueue.take () {try {// Fetch an element from the blocking queue. System.out.println("Queue surplus" + queue.size() + "The element"); 
      } catch (InterruptedException e) { 
      } } } 
} 
 class Producer extends Thread{
       @Override public void run() {
        while (trueQueue.put (1); // Insert an element into the blocking queue. System.out.println("Queue remaining space:" + (size - queue.size())); 
         } catch (InterruptedException e) {} }} 
}
}
Copy the code

4. ArrayBlockingQueue, CountDownLatch class

  1. ArrayBlockingQueue: An array-based implementation of a blocking queue that requires a specified capacity when constructed. The current thread is blocked when trying to add an element to a full queue or remove an element from an empty queue.
  2. CountDownLatch: A synchronization counter, which is a thread utility class that allows one or more threads to wait for other threads

5. Condition

Condition is an interface with await and signal methods, similar to Object wait and notify. Condition is obtained from lock: Condition Condition = lock.newCondition(); Compared with wait and notify of Object, Condition control is more flexible and can meet the purpose of arousing a certain thread

process


0. Three states of the process

  1. Ready state: Transitions from ready state to running state when CPU scheduling is obtained
  2. Running status: The CPU changes from running state to ready state when the CPU time slice is used up
  3. Blocked: To enter a blocked state waiting for an event to occur, and then switch from the blocked state to the ready state

1. Process synchronization and mutual exclusion

  1. Mutual exclusion: Two processes cannot use the same critical resource at the same time, so the other process can use it only when one process runs out. This phenomenon is called mutual exclusion between processes.
  2. For mutually exclusive resources, when process A reaches this point and process B is performing operations on the resource, process A stops and waits for the operations to complete before continuing. This is called synchronization between processes

2. The necessary conditions for a deadlock to occur

  1. Mutually exclusive: A resource can only be used by one process at a time
  2. Non-dispossession condition: a resource can only be released by the process that owns it, and cannot be seized by another process
  3. Request and hold conditions: a process that has already held at least one resource requests a new resource that has already been occupied by another process. In this case, the requesting process blocks but holds on to other resources that have already been acquired
  4. Loop waiting condition: When there is only one resource of each type, there must be a process – resource ring chain when deadlock occurs

Class loading


Describe how the JVM loads class files

The class loader loads a class file into JVM memory with the specified fully qualified name and turns it into a class object.

The type of loader

  1. Bootstrap ClassLoader: Implemented by native code, it is responsible for loading into memory the class libraries stored in the

    \lib directory or the path specified by the -xbootclasspath parameter
  2. Bootstrap: is responsible for loading all class libraries in the

    \lib\ext directory or in the path specified by the java.ext.dirs system variable.
  3. Application ClassLoader: Java implementation responsible for loading specified class libraries on the user’s classpath. We can use this ClassLoader directly. In general, if we don’t have a custom class loader this is the default.
  4. Custom classloaders: Custom classloaders are sometimes needed when classes are encrypted for security or loaded remotely (from a server). The loadClass method already implements parent delegate mode. When the parent class fails to load successfully, the findClass method of the current class is called, so we generally override this method.

The loading process

  1. Class loaders use the parent delegate model for loading: each time by first delegating the parent class loader to load, when the parent class loader cannot load, then load itself.
  2. The life cycle of a class can be divided into seven stages: load -> connect (validate -> Prepare * (allocate memory for static variables and set default initialization values) * -> parse * (replace symbolic references with direct references) *) -> initialize -> Use -> unload

1. Why is the parent delegate pattern used for class loading? Are there any scenarios that break this pattern

  1. Use parental delegate mode to ensure that the class is loaded only once
  2. We can use a custom class loader to load a class of the same name, which prevents the system’s parent delegate pattern from loading

2. ClassLoader isolation issues

  1. The only way the JVM and Dalvik recognize a class is the ClassLoader ID + PackageName + ClassName
  2. Two identical classes may be incompatible with two Classloaders

Reflection and paradigm


0. Principle and function of reflection

  1. The class object class is used to obtain information about the class, create corresponding objects, or call methods
  2. Reflection is required for App dynamic loading or for calling other object private methods in Android

1. Method of obtaining class objects

  1. String.class: static blocks and dynamic constructors are not executed
  2. “hello”.getClass(); : Executes static blocks and dynamic building blocks
  3. Class.forName(“java.lang.String”); : Executes static blocks, not dynamic constructors

2. How to create objects through reflection

  1. String.class.newInstance();
  2. String.class.getConstrutor(Stirng.class).newInstance(“hello word”);

3. How to get and set the value of an object’s private field through reflection

  1. The (Field) object is obtained through the getDeclaredField() method of the class object
  2. Call the setAccessible(true) method of the Field object to make it accessible
  3. Get /set the value of a field using the get/set method

4. Call object methods through reflection

  1. The Method object is obtained through the getMethod Method Method of the class object
  2. Invoke the invoke () method of the object

5. Paradigm

  1. Stereotypes can be used for class definitions and method definitions
  2. The implementation of a stereotype is done by erasing, which means that the stereotype information is erased after compilation

6. The wildcard

  1. Wildcards are used in two ways:? Extends A and b? super A
  2. ? Extends A means? The upper bound of is A, and it’s not clear what type is appropriate for fetching, so it must be of type A, right
  3. ? Super A stands for? The lower bound of alpha is A, it’s not clear what type is suitable for insertion, must be able to insert A, right

7. Annotations

Annotations are available at one of three levels: source, class, or runtime; Butternife is a class file level reference: https://blog.csdn.net/javazejian/article/details/71860633 https://blog.csdn.net/u013045971/article/details/53509237 https://www.cnblogs.com/likeshu/p/5526187.html

The resources

Java Interview Questions (part 1)

http://www.jcodecraeer.com/a/chengxusheji/java/2015/0206/2421.html