Java knowledge sorting and java knowledge interview

Source: Internet
Author: User

Java knowledge sorting and java knowledge interview

1. What are the features of object-oriented

Inheritance, encapsulation, polymorphism, abstraction

2. What is the mechanism for implementing polymorphism in Java?

Inheritance and interfaces

3. Types of exceptions in Java

3.1 According to the time when the exception needs to be handled, it is divided into compile-time exceptions (CheckedException) and runtime exceptions (RuntimeException ).

3.2 There are two methods to handle exceptions during compilation:

(1) If the current method knows how to handle this exception, try... Catch Block to handle this exception.

(2) If the current method does not know how to handle the exception, the exception is thrown when the method is defined.

3.3 runtime exceptions. Explicit declaration or capture will significantly affect the readability and Running Efficiency of the program. Therefore, the system automatically detects and delivers the exceptions to the default exception handling program, of course, if there are processing requirements, you can also explicitly capture them.

4. Java Data Type

4.1what are the basic data types of Java? Each occupies several bytes.

Byte 1 char 2 short 2 int 4 float 4 double 8 long 8 boolean 1

4.2ing is the basic data type? Can it be inherited?

String is a reference type, which is implemented using a char array at the underlying layer. Because String is a final class, the class modified by final in java cannot be inherited, so String cannot be inherited.

5. Java IO

5.1.Java has several types of streams

Byte stream and byte stream. Byte streams are inherited from InputStream and OutputStream. bytes streams are inherited from InputStreamReader and OutputStreamWriter.

How to convert a 5.2-byte stream into a two-byte stream

Byte input stream character input stream is implemented through InputStreamReader. The constructor of this class can be passed into the InputStream object.

The Byte output stream character output is implemented by OutputSreamWriter. The constructor of this class can be passed into the OutputStream object.

6. Java Collection

6.1 is ArrayList, HashSet, and HashMap thread-safe? What if I don't want a thread-safe set?

No lock is applied to each method, and the thread is obviously insecure.

In the collection, Vector and HashTable are thread-safe.

The Collections tool class provides related APIs to make the above three insecure sets safe, as shown below:

Collections. synchronizedCollection (c)

Collections. synchronizedList (list)

Collections. synchronizedMap (m)

Collections. synchronizedSet (s)

6.2 how are the differences between a concurrent set and a common set?

ConCurrentHashMap, concurrent1_queue, and concurrent1_deque are common concurrent sets. The concurrent set is located in the java. util. concurrent package, is only after jdk1.5, the main author is Doug Lea (http://baike.baidu.com/view/3141057.http) completed.

Java contains common sets, synchronous (thread-safe) sets, and concurrent sets. A common set has the highest performance, but does not guarantee the security of multiple threads and the reliability of concurrency. The thread-safe set only adds the synchronized synchronization lock to the set, seriously sacrificing performance and reducing the concurrency efficiency, concurrent sets not only ensure the security of multithreading but also improve the efficiency of concurrency through complicated policies.

ConcurrentHashMap is the implementation of thread-safe HashMap. The default constructor also has the initialCapacity and loadFactor attributes, but there is also a concurrencyLevel attribute. The default values of the three attributes are 16, 0.75, and 16, respectively. The lock Segmentation technology is used internally to maintain the lock Segment array and store the Entity [] array in the Segment array. The internal hash algorithm distributes data evenly among different locks.

Put operation: synchronized is not added to this method. First, hash key. hashcode to get the hash value of the key. The Hash operation algorithm is different from the map algorithm. Based on the hash value, the algorithm calculates and obtains the Segment object (inherited from ReentrantLock) in the corresponding array ), then, call the put Method of the Segment object to complete the current operation.

ConcurrentHashMap divides multiple segments based on concurrencyLevel to store the key-value. This prevents the entire array from being locked every put operation. By default, it is best to allow 16 concurrent and non-blocking operation set objects for 16 threads to minimize the blocking phenomenon during concurrency.

Get (key)

First, perform the hash operation on key. hashCode, locate the corresponding Segment object based on its value, and call its get method to complete the current operation. The get operation of Segment first obtains the HashEntry at the corresponding position on the array by bitwise AND operation through the hash value and the value of the object array size minus 1. In this step, the size of the object array may change, and the HashEntry at the corresponding position on the array may cause inconsistency. How can ConcurrentHashMap be guaranteed?

Changes in the size of an object array may occur only in the put operation. Because the HashEntry object array corresponds to a variable of the volatile type, the size of a HashEntry object array can be changed, the read operation shows the size of the latest object array.

After obtaining the HashEntry object, how can we ensure that the object on the linked list consisting of it and its next attribute will not change? This ConcurrentHashMap uses a simple method, that is, the hash, key, and next attributes in the HashEntry object are all final, this means that there is no way to insert a HashEntry object to the center or end of the linked list consisting of the next attribute. This ensures that the linked list built based on the next attribute will not change after the HashEntry object is obtained.

ConcurrentHashMap stores data in 16 segments by default, and the 16 segments respectively hold different locks. The lock is only used for put, remove, and other operations to change the set object, based on the immutability of volatile and HashEntry linked lists, the read locks are not implemented. These methods enable ConcurrentHashMap to maintain excellent concurrency support, especially for the Map that reads more frequently than inserts and deletes, these methods are also a reflection of the deep understanding of the Java Memory Model and concurrency mechanism.

7. Java Multithreading

7.1 create multiple threads

Java. lang. an instance of the Thread class is a Thread, but it needs to call java. lang. the Runnable interface is used for execution. Because the Thread class itself is the called Runnable interface, it can inherit java. lang. thread class or directly implement the Runnable interface to override the run () method to implement the Thread.

7.2 what are the differences between the wait and sleep methods in java?

The biggest difference is that wait releases the lock while waiting, and sleep keeps holding the lock. Wait is usually used for interaction between threads, and sleep is usually used to suspend execution.

7.3synchronized and volatile keywords

Once a shared variable (the member variable of the class and the static member variable of the class) is modified by volatile, it has two layers of semantics:

(1) ensure the visibility when different threads operate on this variable, that is, a thread modifies the value of a variable, which is immediately visible to other threads.

(2) re-sorting of commands is prohibited.

Volatile essentially tells the jvm that the value of the current variable in the register (Working Memory) is uncertain and needs to be read from the main memory;

Synchronized is used to lock the current variable. Only the current thread can access the variable. Other threads are blocked.

(1) volatile can only be used at the variable level; synchronized can be used at the variable, method, and class level.

(2) volatile can only realize variable modification visibility, but cannot guarantee atomicity. synchronized can ensure variable modification visibility and atomicity.

(3) volatile will not cause thread blocking; synchronized may cause thread blocking.

(4) variables marked by volatile are not optimized by the compiler; variables marked by synchronized can be optimized by the compiler.

7.4 what is a thread pool and how to use it

The thread pool puts multiple thread objects in a container in advance. When using the thread, you can directly get the thread from the pool instead of the new thread, saving the time for opening up the Sub-thread, this improves code execution efficiency.

In JDK java. util. concurrent. Executors, a static method is provided to generate multiple thread pools:

ExecutorService newCanchedThreadPool = Excutors. newCachedThreadPool ();

ExecutorService newFixedThreadPool = Excutors. newFixedThreadPool (4 );

ScheduledExecutorService newScheduledThreadPool = Executors. newScheduledThreadPool (4 );

ExecutorService newSingleThreadExecutor = Executors. newSingleThreadExecutor ();

Then, call their execute method.

7.5 understanding of Thread Pool

Describes how to use the thread pool, the benefits of the thread pool, and the startup policy of the thread pool.

The rational use of the thread pool brings three benefits:

1. reduce resource consumption. Reuse created threads to reduce the consumption caused by thread creation and destruction.

Second, increase the response speed. When a task arrives, the task can be executed immediately without waiting for the thread to be created.

Third: Improve the manageability of threads. A thread is a scarce resource. unlimited creation will not only consume system resources, but also reduce system stability. The thread pool can be used for unified allocation, tuning, and monitoring.

7.6 thread pool startup Policy

(1) When the thread pool is just created, there is no thread in it. The task queue is passed in as a parameter. However, even if there are tasks in the queue, the thread pool will not execute them immediately.

(2) When the execute () method is called to add a task, the thread pool will make the following judgment:

A. If the number of threads being executed is smaller than corePoolSize, immediately create a thread to run the task;

B. If the number of threads being executed is greater than or equal to corePoolSize, put the task into the queue;

C. If the queue is full at this time and the number of threads being executed is smaller than maximumPoolSize, create a thread to run the task;

D. If the queue is full and the number of running threads is greater than or equal to maximumPoolSize, the thread pool throws an exception and notifies the caller that the task cannot be accepted ".

(3) When a thread completes a task, it takes the next task from the queue for execution.

(4) When a thread has nothing to do and exceeds a certain period of time (keyAliveTime), the thread pool will judge that if the number of currently running threads is greater than corePoolSize, the thread will be stopped. Therefore, after all the tasks in the thread pool are completed, it will eventually contract to the coorPoolSize.

7.7 how to control the size of a method that allows concurrent access to threads?

You can use Semaphore control to initialize n signals and run semaphore in the thread. the acquire () request can only have up to n threads for concurrent access, and waits in queue when n threads are redundant. After the thread completes, release the signal so that the new thread can be used.

8. Reflection in Java

8.1Java reflection Comprehension

Reflection in Java is first able to get the bytecode of the class to be reflected in Java. There are three methods to get the bytecode: 1. class. forName (className) 2. class Name. class3.this. getClass (). Then, the methods, variables, and constructors in bytecode are mapped to corresponding methods, Filed, Contructor, and other classes. These classes provide a wide range of methods to be used.

8.2 what are the differences between dynamic and static Proxies?

Static proxy usually only acts as a proxy for one class. Dynamic proxy is used to represent multiple implementation classes under an interface.

The static proxy knows in advance what the proxy is, but the dynamic proxy does not know what the proxy is, and it is only known at runtime.

Dynamic Proxy is the invoke method that displays the InvocationHandler interface in JDK, but note that the Proxy is an interface, that is, the service class must implement the interface and get the Proxy object through newProxyInstance in Proxy.

There is also a dynamic proxy CGLIB. The proxy is a class, and the business class inheritance interface is not required. The derived subclass is used to implement the proxy. You can modify the class by dynamically modifying the bytecode at runtime.

AOP programming is implemented based on dynamic proxies. For example, the famous Spring framework and Hibernate framework are examples of dynamic proxies.

9. collection mechanism in Java

9.1.Java garbage collection mechanism and common algorithms

Sun only defines the garbage collection mechanism rules rather than its implementation algorithms. Therefore, the algorithms used by virtual machines produced by different manufacturers are also different.

GC (Garbage Collector) must first discover useless objects before recycling objects. How can we locate useless objects? The common search algorithm is as follows:

(1) Reference Counter algorithm (obsolete)

The counter reference algorithm sets a counter for each object. When this object is referenced somewhere, the counter + 1. When the reference fails, the calculator-1, when the counter is 0, the JVM considers that the object is no longer used and is "junk.

The reference counter is simple and efficient, but it cannot solve the problem of circular reference (Object A references object B, object B references object A, but object, object B is no longer referenced by any other object. At the same time, the increase or decrease of counter brings a lot of extra overhead. Therefore, after JDK1.1, this algorithm will no longer be used.

(2) root search algorithm (used)

The root search algorithm uses some "GC Roots" objects as the starting point to start searching from these nodes. The paths used for searching become Reference chains ), when an object is not connected by the reference chain of GC Roots, this object is unavailable.

GC Roots objects include:

A. Objects referenced in the VM stack (the local variable table in the stack frame.

B. Objects referenced by class static attributes in the method area.

C. Objects referenced by constants in the method area.

D. Objects referenced by JNI (Native method) in the local method stack.

After finding useless objects through the above algorithm, it is the recycling process. The recycling algorithm is as follows:

(1) Mark-clearing algorithm (the algorithm used by DVM)

The mark-clearing algorithm consists of two phases: "mark" and "clear ". In the tag phase, identify all objects to be recycled and mark them. The purge phase follows the markup phase to clear unavailable objects. The mark-clearing algorithm is a basic collection algorithm. The efficiency of the Mark-clearing phase is not high, and a large amount of discontinuous space is generated after the algorithm is clear. In this way, when the program needs to allocate large memory objects, you may not be able to find enough continuous space.

(2) Copying)

The replication algorithm divides the memory into two equal parts. Each time one of them is used, when garbage collection is performed, the surviving objects are copied to the other, and the entire memory is cleared. The replication algorithm is easy to implement and runs efficiently. However, because only half of the algorithm can be used at a time, the memory usage is not high. The current JVM uses the replication method to collect the New Generation. Most of the objects (98%) in the new generation are killed overnight, so the ratio of the two memory blocks is not (about ).

(3) Mark-Compact)

The markup-sorting algorithm is the same as the markup-clearing algorithm, but the markup-sorting algorithm does not copy a surviving object to another memory, but moves the surviving object to one end of the memory, then, the memory outside the boundary is recycled directly. The tag-sorting algorithm improves the memory utilization and is suitable for the old age when the collection object remains alive for a long time.

(4) Generational Collection)

Generational collection divides the memory into new and old generations based on the survival time of objects. Based on the Survival characteristics of each generation of objects, each generation uses different garbage collection algorithms. The new generation uses the replication algorithm and the old generation uses the tag-sorting algorithm. The implementation of spam algorithms involves a lot of program details, and the implementation methods of different virtual machine platforms are also different.

9.2.JVM memory structure and Memory Allocation

(1) java Memory Model

Java Virtual Machine divides its memory into three logical parts: Method Area, Java stack, and Java stack.

A. the method area is statically allocated. The Compiler binds variables to a storage location and these bindings will not change during runtime. Constant pool, named constants, String constants, and static variables in the source code are stored in the method area.

B. Java Stack is a logical concept and features a forward, forward, and backward. The space of a stack may be continuous or discontinuous. The most typical Stack application is a method call. A method frame is created every time a Java Virtual Machine calls a method. After exiting this method, the corresponding method frame is pop ). The data stored in the stack is also determined at runtime.

C. Java heap allocation means that the memory management model for Bucket allocation and recovery is implemented at runtime in random order. The size, quantity, and life cycle of the data stored in the heap are often uncertain during compilation. The memory of Java objects is always allocated in heap.

(2) Java Memory Allocation

A. The basic data type is directly allocated in the stack space.

B. The formal parameters of the method are directly allocated in the stack space. After the method is called, it is reclaimed from the stack space.

C. Reference data types, which must be created using new. That is, an address space is allocated in the stack space, and class variables of objects are allocated in the heap space.

D. Reference parameters of the method. Allocate an address space in the stack space and point it to the object area of the heap space. After the method is called, it is reclaimed from the stack space.

E. When the local variable is new, space is allocated in the stack space and heap space. When the lifecycle of the local variable ends, the stack space is recycled immediately, and the heap space is waiting for GC to be recycled.

F. The actual parameter passed in when the method is called. Now the stack space is allocated and is released from the stack space after the method call is completed.

G. The String constant is allocated in the DATA area, and this is allocated in the heap space.

H. array: allocate the array name in the stack space, and allocate the actual size of the array in the heap space.

9.3.what types of reference are available in Java?

In Java, object references are divided into four levels, from high to low: strong reference, soft reference, weak reference, and virtual reference.

(1) strong references

If an object is strongly referenced, the garbage collector will never recycle it. When the memory space is insufficient, the Java Virtual Machine would rather throw an OutOfMemoryError to terminate the program abnormally, and will not recycle the strongly referenced object without any restrictions.

Java objects are in heap. Objects in heap have strong and object, soft and object, weak and object, virtual and object, and inaccessible object. The order of application strength is strong, soft, weak, and virtual. The most powerful reference of an object is the sum of objects.

String abc = new String ("abc"); // strong reference. abc is strongly comparable.

SoftReference <String> softRef = new SoftReference <String> (abc); // soft reference

WeakReference <String> weakRef = new WeakReference <String> (abc); // weak reference

Abc = null; // abc soft and

SoftRef. clear (); // abc becomes weak

(2) soft reference

If an object only has soft references, the garbage collector will not recycle it if the memory space is sufficient. If the memory space is insufficient, the memory of these objects will be recycled. The object can be used by programs as long as the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive high-speed cache.

Soft references can be used together with a ReferenceQueue. If the referenced objects are recycled by the garbage collector, the Java virtual machine adds this soft reference to the reference queue associated with it.

Soft reference is mainly used for memory-sensitive high-speed cache. All soft references will be cleared before the jvm reports that the memory is insufficient. In this way, gc may have mobile phone soft accessible objects, which may solve the memory shortage problem and avoid memory overflow. The collection depends on the gc algorithm and the available memory size during gc runtime. When the gc decides to collect soft references, perform the following steps: (The above softRef is used as an example)

A. First, set softRef's referent (abc) to null and do not reference the new String ("abc") object in heap.

B. Set the new String ("abc") object in heap to finalizable ).

C. when the finalize () method of the new String ("abc") object in heap is run and the memory occupied by the object is released, softRef is added to its ReferenceQueue (if any).

Note: soft and weak references of ReferenceQueue can be unavailable, but virtual references must be available.

Objects referenced by Soft Reference are not cleared even if there is no Direct Reference. It is cleared until the JVM memory is insufficient and there is no Direct Reference. SoftReference is used to design the objct-cache. In this way, SoftReference not only caches objects, but also does not cause memory insufficiency errors (OutOfMemoryError ).

(3) weak references

If an object only has weak references, the class is dispensable, because the object will be killed whenever it is scanned by gc.

Differences between weak references and soft references: only objects with weak references have a shorter life cycle. When the Garbage Collector thread scans the memory area under its jurisdiction, its memory will be recycled no matter whether the current memory space is sufficient or not. However, since the garbage collector is a thread with a low priority, it may not be able to quickly find objects with weak references.

Weak references can be used together with a ReferenceQueue. If the referenced objects are recycled by the garbage collector, the Java virtual machine adds this weak reference to the associated reference queue.

(4) Virtual Reference

Unlike other centralized references, virtual references do not determine the object lifecycle. If an object only holds a virtual reference, it is the same as no reference and may be recycled by the garbage collector at any time. Virtual references are used to track the activity of objects recycled by the garbage collector.

The difference between Virtual Reference and soft reference and weak reference: Virtual Reference must be used together with the reference Queue (ReferneceQueue. When the garbage collector is preparing to recycle an object, if it finds that it is still a virtual reference, it will assume that the virtual reference is in the reference queue associated with the object before it recycles the object's memory. The program can determine whether a Virtual Reference is added to the reference queue. To check whether the referenced object is to be recycled. If the program finds that a virtual reference has been added to the reference queue, it can take necessary actions before the memory of the referenced object is recycled.

After a Virtual Reference is created, the returned result is always null through the get method. The source code shows that the referenced object is usually written into the referent, but the return result of the get method is null. Interaction with gc: a. Directly sets the new String ("abc") object in heap to finalizable without setting the referent to null ). B. Unlike soft reference and weak reference, add the PhantomReference object to its ReferencQueue and release the virtual accessible object.

10. Java Class Loader

10.1.what types of Java class loaders are there?

(1) The root loader (Bootstrap) --- written in C ++, without the source code

(2) extended Class Loader --- loading location: in jre \ lib \ ext

(3) System (Application) Class Loader (System \ App) --- loading location: In classpath

(4) custom loader (must inherit ClassLoader)

10. 2. When will the class be initialized?

(1) create a class instance, that is, a new object.

(2) access a static variable of a class or interface, or assign a value to the static variable.

(3) Call static methods of the class.

(4) reflection.

(5) initialize a subclass of a class.

(6) The JVM startup class, that is, the class with the same file name and class name.

Only these six cases will lead to class initialization.

10. 3. class initialization steps

(1) If the class has not been loaded or linked, load and link it first.

(2) If this class has a direct parent class and the class has not been initialized (Note: In a class loader, the class is intelligently initialized once ), then initialize the direct parent class (not applicable to interfaces ).

(3) If there are initialization statements (such as static variables and static blocks) in the class, execute these initialization statements in sequence.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.