Java Interview Dry

Source: Internet
Author: User
Tags semaphore visibility volatile

Java basic knowledge collection and collation

1. What are the characteristics of object-oriented?

Inheritance, encapsulation, polymorphism, abstraction

What is the mechanism to achieve polymorphism in 2.Java?

Inheritance and Interfaces

What kinds of anomalies are classified in 3.Java

3.1 The timing of exceptions needs to be handled into compile-time exceptions (checkedexception) and run-time exceptions (RuntimeException).

3.2 There are two ways to handle compile-time exceptions:

(1) The current method knows how to handle the exception, and the Try...catch block is used to handle the exception.

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

3.3 Runtime exceptions, if explicitly declared or captured, will have a significant impact on the readability and operational efficiency of the program, so it is automatically detected by the system and handed over to the default exception handlers, although they can also be explicitly captured if there are processing requirements.

Data type of 4.Java

What are the basic data types of 4.1Java, each of which takes up a few bytes

Byte 1 char 2 short 2 int 4 float 4 Double 8 long 8 Boolean 1

Is 4.2ing a basic data type? Can it be inherited?

String is a reference type, and the underlying is implemented with a char array. Because string is the final class, a class that is final decorated in Java cannot be inherited, so string certainly cannot be inherited.

5.Java of IO

There are several types of streams in 5.1.Java

Byte stream and character stream. Byte streams inherit from InputStream and OutputStream, and character streams inherit from InputStreamReader and OutputStreamWriter.

How to convert 5.2 byte stream to character stream

The byte input flow character input stream is implemented by InputStreamReader and the constructor of the class can pass in the InputStream object.

Byte output stream character output streams are implemented by Outputsreamwriter, and the constructors of this class can pass in the OutputStream object.

Collection of 6.Java

6.1ArrayList, HashSet, HashMap is thread-safe? What if you don't want a thread-safe collection?

Each method is not locked, and is obviously thread insecure.

Vectors and hashtable are thread-safe in the collection.

The Collections tool class provides the relevant API to make the above 3 unsafe collections safe, as follows:

Collections.synchronizedcollection (c)

Collections.synchronizedlist (list)

Collections.synchronizedmap (M)

Collections.synchronizedset (s)

6.2 How do concurrent collections differ from normal collections?

Concurrent collections are common in Concurrenthashmap, Concurrentlinkedqueue, Concurrentlinkeddeque, and so on. The concurrent collection is located under the Java.util.concurrent package and is jdk1.5 after the main author is Doug Lea (http://baike.baidu.com/view/3141057.http).

There are common collections, synchronous (thread-safe) collections, and concurrent collections in Java. Common collections typically have the highest performance, but do not guarantee the security of multithreading and the reliability of concurrency. The thread-safe collection simply adds synchronized synchronous locks to the set, seriously sacrificing performance, and the efficiency of concurrency is lower, while concurrent sets can not only ensure the security of multithreading and improve the efficiency of concurrency.

Concurrenthashmap is a thread-safe implementation of the HASHMAP, the default constructs also have Initialcapacity and Loadfactor properties, but also a Concurrencylevel property, the three-property default value is 16, 0.75 and 16. Its internal use of lock segmentation technology, maintain the lock segment array, in the segment array and stored in the entity[] array, the internal hash algorithm to distribute the data more evenly in different locks.

Put operation: Do not add synchronized on this method, first hash operation of Key.hashcode, get key hash value. Hash operation algorithm and map, based on this hash value to calculate and get its corresponding array of segment object (inherit from Reentrantlock), and then call this segment object's put method to complete the current operation.

Concurrenthashmap divides multiple segment based on Concurrencylevel to store key-value, thus avoiding locking the entire array for each put operation. By default, it is best to allow 16 threads to concurrently block the collection object without blocking, minimizing congestion when concurrency occurs.

Get (Key)

First, the Key.hashcode is hashed, the corresponding segment object is found based on its value, and the Get method is called to complete the current operation. The get operation of segment first obtains the hashentry of corresponding position on the array by the bitwise AND operation of the value of the hash value and the object array size minus 1. In this step, it is possible to change the size of the object array and the hashentry of the corresponding position on the array, so how is concurrenthashmap guaranteed?

The change in the size of the object array is only possible with a put operation, because the variable of the Hashentry object array is of type volatile, so you can guarantee that the Hashentry object array size changes, and the read operation can see the most recent object array size.

After acquiring the Hashentry object, how can it be ensured that the object on the linked list that it and its next property does not change? This concurrenthashmap takes a simple approach, that is, the hash, key, and next properties in the Hashentry object are final, This means that there is no way to insert a Hashentry object into the list or end of a linked list that is based on the next attribute. This ensures that when the Hashentry object is acquired, the linked list that is built on the next property is not changed.

Concurrenthashmap By default, the data is divided into 16 segments for storage, and 16 segments hold their own different lock segment, lock only for put and remove to change the collection object operation, The invariance of volatile and hashentry linked lists enables the non-locking of reads. These methods allow Concurrenthashmap to maintain excellent concurrency support, especially for maps that are more frequent than insertions and deletions, and which are used in a way that is a reflection of the deep mastery of Java memory models and concurrency mechanisms.

Multithreading in 7.Java

7.1 Multi-Threading two ways to create

An instance of the Java.lang.Thread class is a thread but it needs to invoke the Java.lang.Runnable interface to execute, because the thread class itself is the runnable interface of the call, so you can inherit the Java.lang.Thread class or implement the Runnable interface directly to override The run () method implements the thread.

7.2 What is the difference between the wait and sleep methods in Java?

The biggest difference is that wait waits for the lock to be released while sleep holds the lock. Wait is typically used for inter-thread interaction, and sleep is typically used to pause execution.

Role of 7.3synchronized and volatile keywords

Once a shared variable (a member variable of a class, a static member variable of a class) is modified by volatile, then there are two layers of semantics:

(1) Ensure the visibility of different threads operating on this variable, that is, one thread modifies the value of a variable, and the new value is immediately visible to other threads.

(2) command reordering is prohibited.

The volatile nature is to tell the JVM that the value of the current variable in the register (working memory) is indeterminate and needs to be read from main memory;

Synchronized is locking the current variable, and other threads are blocked only if the variable is accessible to the front thread.

(1) Volatile can only be used at variable levels; Synchronized can be used at variable, method, and class level.

(2) volatile can only realize the change of the visibility of variables, and does not guarantee atomicity, synchronized can guarantee the change of the visibility of variables and atomicity.

(3) volatile does not cause thread blocking, and synchronized can cause thread blocking.

(4) Volatile tagged variables are not optimized by the compiler; Synchronized tagged variables can be optimized by the compiler.

7.4 What is a thread pool and how to use it

The thread pool is to put more than one thread object into a container in advance, when it is used, it can be taken directly to the pool without the new thread, which saves the time of opening up the sub-thread and improves the execution efficiency of the code.

A static method for generating multiple thread pools is provided in the java.util.concurrent.Executors of the JDK:

Executorservice Newcanchedthreadpool = Excutors.newcachedthreadpool ();

Executorservice Newfixedthreadpool = Excutors.newfixedthreadpool (4);

Scheduledexecutorservice Newscheduledthreadpool = Executors.newscheduledthreadpool (4);

Executorservice newsinglethreadexecutor = Executors.newsinglethreadexecutor ();

Then call their Execute method.

Understanding of the 7.5 thread pool

Talking about how a thread pool is used, the benefits of a thread pool, and the startup strategy of the thread pool

The rational use of the thread pool can bring three benefits:

First: Reduce resource consumption. Reduce the consumption caused by thread creation and destruction by reusing the threads that have been created.

Second: Improve 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. Threads are scarce resources that, if created indefinitely, not only consume system resources, but also reduce system stability, using a thread pool for uniform allocation, tuning, and monitoring.

7.6 Thread pool Start-up strategy

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

(2) when the Execute () method is called to add a task, the thread pool makes the following judgment:

A. If the number of threads executing is less than corepoolsize, then create the thread to run the task immediately;

B. If the number of threads executing is greater than or equal to Corepoolsize, the task is placed in the queue;

C. If the queue is full at this time, and the number of threads executing is less than maximumpoolsize, then create a thread to run the task;

D. If the queue is full and the number of threads running is greater than or equal to maximumpoolsize, then the thread pool throws an exception telling the caller to "no longer accept the task."

(3) When a thread finishes a task, it takes the next task from the queue to execute.

(4) When a thread has nothing to do, more than a certain amount of time (keyalivetime), the thread pool will determine if the number of threads currently running is greater than corepoolsize, then the threads will be stopped. So when all the thread pool tasks are completed, it eventually shrinks to the size of the coorpoolsize.

7.7 How do I control the size of a method that allows concurrent access to threads?

You can use the semaphore control, which is the signal, initialize n signals, in the thread, run Semaphore.acquire () request requests, so that only a maximum of n threads concurrently access, the extra n threads are queued. After the thread completes, the signal is released so that the new thread can be used.

Reflection in 8.Java

Understanding of reflection in 8.1Java

The reflection in Java is first to be able to get to the Java to reflect the class's byte code, obtains the byte code to have three methods, 1.class.forname (ClassName) 2. Class name. Class3.this.getClass (). The methods, variables, constructors, etc. in bytecode are then mapped into the appropriate methods, Filed, Contructor and other classes, which provide a rich way to be used.

8.2 What is the difference between dynamic static agents and what scenarios are used?

Static proxies typically only represent one class, and a dynamic proxy is a proxy for multiple implementation classes under an interface.

Static agents know in advance what to proxy, and dynamic agents do not know what to proxy, only at run time to know.

Dynamic proxy is the Invoke method that displays the Invocationhandler interface in the JDK, but the agent is the interface, that is, the business class must implement the interface, through the proxy in the newproxyinstance to get the agent object.

There is also a dynamic proxy cglib, the proxy is the class, do not need the business class to inherit the interface, through the derived subclass to implement the proxy. By dynamically modifying bytecode at run time, the purpose of modifying the class is achieved.

AOP programming is based on dynamic agents, such as the famous Spring Framework, hibernate framework, etc. are examples of the use of dynamic agents.

Recycling mechanism in 9.Java

9.1.Java garbage collection mechanism and common algorithms

Sun company only defined the garbage collection mechanism rules and not limited to its implementation algorithm, so different manufacturers of virtual machines used by the same algorithm.

The GC (garbage Collector) must first discover those useless objects before reclaiming the object, how to find out what to locate these useless objects? The usual search algorithm is as follows:

(1) Reference counter algorithm (deprecated)

The reference counter algorithm is to set a counter for each object, when there is a place to reference this object, counter +1, when the reference fails, the calculator-1, when the counter is 0, the JVM thinks the object is no longer used, is "garbage".

The reference counter is simple and efficient, but it does not solve circular reference problems (a object references B objects, B objects reference a object, but a A, A/b object is no longer referenced by any other object), while the increment and decrease of each counter brings a lot of extra overhead. So after the JDK1.1, the algorithm is no longer used.

(2) Root search algorithm (use)

The root search algorithm is based on some "GC Roots" objects, starting from these nodes, searching through the path to become the reference chain (Reference Chain), when an object is not connected by the GC Roots reference chain, this object is not available.

GC roots objects include:

A. The referenced object in the virtual machine stack (the local variable table in the stack frame).

B. The object referenced by the class static property in the method area.

C. The object referenced by a constant in the method area.

D. The object referenced by the JNI (native method) in the local method stack.

After searching for useless objects through the above algorithm, it is the recycling process, the recovery algorithm is as follows:

(1) Mark-Purge Algorithm (MARK-SWEEP) (algorithm used by DVM)

The tag-purge algorithm consists of a single phase: "Mark" and "clear". In the tagging phase, identify all objects to be reclaimed and mark them. The purge phase is immediately followed by the Mark phase, which identifies the unavailable object cleanup. The mark-and-sweep algorithm is the underlying collection algorithm, and the mark and purge phases are inefficient and clear, resulting in a large amount of discontinuous space, so that when the program needs to allocate large memory objects, it may not be able to find enough contiguous space.

(2) Copy algorithm (Copying)

The algorithm is to divide the memory into two blocks of equal size, each time using one piece, and when garbage is collected, copy the surviving object to the other, and then clean up the whole piece of memory. The replication algorithm is simple and efficient, but the memory utilization is not high because only half of them can be used at a time. Now the JVM collects the new generation by means of replication, because most of the objects (98%) in the Cenozoic are dying, so the ratio of two pieces of memory is not 1:1 (about 8:1).

(3) Labeling-sorting algorithm (mark-compact)

The tag-collation algorithm is the same as the tag-purge algorithm, but the tag-collation algorithm does not copy the surviving object to another memory, but moves the surviving object to one end of the memory, and then reclaims the memory outside the boundary directly. The tagging-grooming algorithm improves memory utilization and is suitable for older generations where objects are collected for longer periods of time.

(4) collection of generational (generational Collection)

Generational collection is based on the survival time of the object to divide the memory into Cenozoic and Laosheng generation, according to the survival characteristics of each generation object, each generation adopts different garbage collection algorithm. The new generation adopts the replication algorithm, and the Laosheng uses the marker-collation algorithm. The implementation of the garbage algorithm involves a lot of procedural details, and the different methods of implementing the virtual machine platform vary.

9.2.JVM of memory structure and memory allocation

(1) Java memory model

The Java Virtual machine has roughly three logical parts of its governing memory: The method area, the Java stack, and the Java heap.

A. The method area is statically allocated, and the compiler binds the variables to a storage location, and the bindings no longer change when they run. Constant pools, in which named constants, string constants, and static variables in the source code are saved in the method area.

B.java stack is a logical concept, characterized by LIFO. The space of a stack may be contiguous, or it may be discontinuous. The most typical stack application is the invocation of a method, and the Java Virtual machine creates a method frame (frame) each time a method is called, and the corresponding method frame is ejected (pop) when the method exits. The data stored in the stack is also determined at run time.

The C.java heap allocation (heap allocation) means a memory management model that allocates and reclaims storage space at run time in a random order. The data stored in the heap is often of a size, quantity, and lifetime that cannot be determined at compile time. The memory of the Java object is always allocated in the heap.

(2) Java memory allocation

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

B. The formal parameters of the method, which are allocated directly in the stack space, are reclaimed from the stack space when the method call is complete.

C. The reference data type needs to be created with new, that is, allocating an address space in the stack space and allocating the class variables of the object in the heap space.

D. The reference parameter of the method, allocates an address space in the stack space, and points to the object area of the heap space, when the method call is finished and reclaimed from the stack space.

e. When the local variable new comes out, allocates space in the stack space and heap space, when the local variable life cycle ends, the stack space is immediately reclaimed, and the heap space area waits for GC to reclaim.

F. The actual arguments passed in when the method is called, and now the stack space is allocated, freed from the stack space after the method call is complete.

G. String constants are allocated in the data area, this is allocated in the heap space.

H. Arrays are allocated array names in the stack space, and the actual size of the array is allocated in the heap space.

What are the reference types in 9.3.Java?

There are four levels of references to objects in Java, with four levels from high to low: strong references, soft references, weak references, and virtual references.

(1) Strong references

If an object is strongly referenced by a person, the garbage collector never reclaims it. When there is not enough memory space, the Java virtual machine would rather throw a outofmemoryerror error, cause the program to terminate abnormally, and not rely on the random recycling of the strongly referenced object Ali to solve the memory shortage problem.

Java objects are in the heap, with objects in the heap that have strong and accessible objects, soft and accessible objects, weak and accessible objects, virtual objects, and unreachable objects. The strength, weakness and weakness of the application are strong, soft, weak and imaginary. The most powerful reference to the object that the object belongs to.

String abc = new string ("abc");//strong reference, ABC is strong and accessible

softreference<string> softref = new softreference<string> (ABC);//Soft reference

weakreference<string> weakRef = new weakreference<string> (ABC);//Weak reference

ABC=NULL;//ABC Soft and accessible

Softref.clear ();//abc becomes weak and accessible

(2) Soft reference

If an object has only soft references, then if there is enough memory space, the garbage collector will not reclaim it, and if the memory space is insufficient, the memory of those objects will be reclaimed. The object can be used by the program as long as it is not reclaimed by the garbage collector. Soft references can be used to implement memory-sensitive caches.

A soft reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the soft reference is reclaimed by the garbage collector, the Java Virtual machine will add the soft reference to the reference queue associated with it.

Soft references are primarily used for memory-sensitive caches. All soft references are cleared before the JVM reports out of memory, so that the GC has the potential to be soft on the phone, potentially resolving memory crunch issues and avoiding memory overflow. When it is collected depends on the GC algorithm and the size of the available memory when the GC is running. The steps to perform when the GC decides to collect soft references are as follows: (Take the above softref as an example)

A. First set Softref's referent (ABC) to null and no longer refer to the new String ("ABC") object in the heap.

B. Set the new String ("ABC") object in the heap to be closed (finalizable).

C. When the Finalize () method of the new String ("ABC") object in the heap is run and the memory occupied by the object is freed, Softref is added to its referencequeue (if any).

Note: Soft and weak references to Referencequeue are optional, but virtual references must be available.

Objects that are referred to by soft Reference are not cleared even if there is no direct Reference. The softreference is used to design objct-cache, until the JVM is out of memory and no direct reference is available. As a result, softreference not only caches the object, it does not cause an out-of-memory error (OUTOFMEMORYERROR).

(3) Weak references

If an object has only a weak reference, that class is an optional object, because whenever the object is scanned by a GC, it will be killed at any time.

The difference between weak and soft references: objects with only weak references have a shorter life cycle. As the garbage collector thread scans the area of memory it governs, once an object with only a weak reference is found, its memory is reclaimed, regardless of whether the current memory space is sufficient or not. However, because the garbage collector is a low-priority thread, objects that have only weak references are not necessarily discovered soon.

A weak reference can be used in conjunction with a reference queue (Referencequeue), and if the object referenced by the weak reference is reclaimed by the garbage collector, the Java Virtual machine adds the weak reference to the reference queue associated with it.

(4) Virtual reference

A virtual reference differs from other set references, and the virtual reference does not determine the life cycle of the object. If an object holds only virtual references, it can be reclaimed by the garbage collector at any time, just as there are no references. Virtual references are primarily used to track activities that objects are reclaimed by the garbage collector.

The difference between a virtual reference and a soft reference and a weak reference: a virtual reference must be used in conjunction with the reference queue (Refernecequeue). When the garbage collector prepares to reclaim an object, if it is found to be a virtual reference, the virtual reference will be made to the reference queue associated with it before the memory of the object is reclaimed. The program can determine whether a virtual reference is added to the reference queue. To see if the object being referenced is being garbage collected. If the program finds that a virtual reference has been added to the reference queue, it can take the necessary action before the memory of the referenced object is recycled.

After a virtual reference is made, the result returned by the Get method is always null, and the source code finds that the virtual reference usually writes the referenced object into referent, except that the Get method returns the result as null. The process of interacting with the GC: A. Do not set referent to NULL to directly set the new String ("ABC") object in the heap to be closed (finalizable). B. Unlike soft and weak references, you first add the Phantomreference object to its referencqueue, and then you release the virtual object.

Class loader for 10.Java

What are the types of 10.1.Java ClassLoader?

(1) Root class loader (Bootstrap)---C + + write, do not see the source code

(2) Extension class loader (Extension)---load location: jre\lib\ext

(3) System (Application) class loader (SYSTEM\APP)---load location: classpath

(4) Custom loader (must inherit ClassLoader)

10.2. When is the class initialized?

(1) Create an instance of the class, that is, the new object.

(2) A static variable that accesses a class or interface, or assigns a value to the static variable.

(3) Call the static method of the class.

(4) Reflection.

(5) Initializes a subclass of a class.

(6) The startup class indicated at the start of the JVM, which is the same class with the same file name and class name.

Only these 6 cases will cause the initialization of the class.

10.3. Initialization steps for classes

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

(2) If the class has a direct parent, and the class has not been initialized (note: In a ClassLoader, class intelligent initialization once), then initialize the direct parent class (not for the interface).

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

Java Interview Dry

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.