1, fianlly code block
In Java exception handling, finally block is to ensure that no matter what happens, finally block code will be executed, because the program executes the return statement means to end the call to the current function and jump out of this function, So finally the code block executes before return, and if there is a return statement in Finally, then the other return statement is overwritten
When the return statement is returned, the the variable defined in the method body does not already exist, so return is not returned directly to the variable, but instead copies a copy and then returns, before returning, the value to be returned is stored in a location before the finally code block is executed, so for the base type of data, Changing the return value in the finally code block has no effect on the returned value and has an impact on the data of the reference type 2, the principle of exception handling
An exception is an abnormal condition or error that occurs when a program runs (not at compile time), and when a program violates a semantic rule, the JVM represents the error as an exception and throws it; the purpose of exception handling is to improve the security and robustness of the program, Java treats exceptions as objects
The base class (java.lang.Throwable) of all exceptions, with exceptions divided into 2 categories: Error and exception
run-time Exceptions and normal exceptions: Error indicates that a very serious error occurred during the run of the program, and that the error is unrecoverable because it is a critical error in the JVM hierarchy, so this error or cause the program to terminate execution exception represents a recoverable exception that the compiler can capture, including checking for exceptions and Run-time exceptions
Check for exceptions: Therefore, exceptions that inherit from exception and are not run as Run-time exceptions are check exceptions, which occur at compile time and are forced by the Java compiler to catch these exceptions (that is, to place code that might have such an exception in a try-catch block)
Checking for exceptions is typically used when an exception occurs that does not result in a program error, and continuing execution after processing relies on unreliable external conditions
Run-time Exception: The compiler did not force it to be caught and processed. If this exception is not handled, it is handled by the JVM when the exception occurs, and after a Run-time exception, the system throws the exception up until the processing code is encountered, and if there is no processing code, it is thrown to the top. Multithreading is thrown using the Thread.run () method, which is thrown in a single thread with the main () method, and if it is multiple threads after throwing an exception, the thread exits, if it is single-threaded, the program exits
attention points for exception handling : Java exception handling uses polymorphism, if the base class is captured in exception handling and then the subclass is captured, then the code block of the subclass is never executed, so the subclass is first captured, the exception is thrown as soon as the base class is captured, and the caught exception is processed. Or you can recover from the error or let the program continue. Custom exception class exception handling based on actual requirements processing, can not be handled on the throw, the final unhandled exception, the JVM will handle 3, Java io flow implementation mechanism
In Java, input and output are referred to as abstract streams (streams can be considered as an ordered set of bytes), the transmission of data between two devices, and the nature of the stream is data transmission, which can be divided into byte streams and character streams according to the type of data being processed;
BYTE stream: in bytes (8bit), contains 2 abstract classes InputStream and OutputStream
Character streams: in characters (16bit), the number of bytes can be read at one time, depending on the code table mapping characters, including 2 abstract classes reader and writer
The main difference between a byte stream and a byte stream is that it does not use the cache when processing data, and the character streams are used to cache 4, Java sockets
Two programs on the network realize the exchange of data through a two-way communication connection, this two-way link is called a socket, in Java, the socket is divided into: connection-oriented Socket Communication protocol (TCP) and Connectionless Socket Communication Protocol (UDP) ; Any socket is uniquely determined by the IP address and port number
TCP-based communication processes: Server-side listen specified port has a connection request the client side sends a connect request server to the server side to send a accept message to the client side
Once the session is established, both server and client can communicate with each other via send and write methods
the life cycle of the socket is divided into three phases: opening the socket using the socket to send and receive data close the socket
In Java, serversocket as server,socket as client 5, Java NIO
Prior to the advent of non-blocking Io, Java is the traditional Socekt to achieve basic network communication capabilities, often blocking (suspend the execution of a thread to wait for a condition to occur); NiO enables non-blocking IO operations via selector, channel, and buffer
Between the client and the selector through two-way channel to communicate, selector implemented a thread to manage multiple channels (selector for all channel polling access, the use of polling in the process of multithreading requests do not need context to switch) 6. Java Serialization
Java provides the way object persistence in 2: Serialization and external serialization
serialization (serialization): in a distributed environment, when communicating remotely, no matter what type of data is transmitted over the network in the form of a binary sequence, serialization is a process of describing an object in a series of bytes. Used to troubleshoot problems that arise when reading and writing to the exclusive
A class that implements serialization must implement the Serializable interface, which is an identity interface: Constructs a ObjectOutputStream (object stream) object using an output stream (such as FileOutputStream) Use this object's WriteObject (Object obj) method to write an Obj object (that is, save its state) using its corresponding input stream for recovery
Characteristics of Serialization: If a class can be serialized, its subclasses can also be serialized static (representing the members of the class), and transient (representing its value does not need to maintain the temporary data of the object), is declared to be not serializable for these 2 types of data members.
because the use of serialization can affect the performance of the system, if it is not required to use, try not to use
You can use the following conditions: The state of the object object that needs to be sent over the network needs to be persisted to the data or file serialization can be replicated deep copy, you can copy the referenced object
deserialization: converting a stream to an object, in the process of serialization and deserialization, by Serialversionuid to determine class compatibility
The advantages of custom serialversionuid: Improve the efficiency of the program (Serialversionuid by computing activities, display declarations can omit the calculation process) to improve the compatibility of programs on different platforms (each platform compiler can be calculated differently, Serialversionuid may be different, display the declaration to avoid this problem) enhance the compatibility of each version of the program (Serialversionuid changes after the class is modified so that the files serialized before the modification cannot be deserialized)
external serialization: more difficult appearance, implement Externalizable interface 7, System.outp.rintln () method
Accepts a variable of type string as an argument by default, and can pass any variable that can be converted to string as a parameter when used
When the input parameter is an object, the object's ToString () method 8 is invoked, and the JVM loads the class file.
The Java language is a dynamic interpretive language in which classes (class) can run only after they are loaded into the JVM, and when the specified program is run, The JVM loads the compiled. class file into memory according to requirements and rules, and organizes it into a finished Java program, which is completed by the class loader (class loader is also a class that essentially reads the class file from the hard disk to memory)
class loading methods are divided into explicit and implicit: Implicit loading : When a program creates an object in such a way as new, it implicitly invokes the ClassLoader of the class to load the corresponding class into the JVM explicitly : by directly calling the Class.forName () method to load the required class into the JVM
In Java, class loading is dynamic and does not load all classes at once, but ensures that the underlying classes that the program runs are loaded completely into the JVM and other classes are loaded when needed;
type of Class |
class Loader |
function |
System class |
Bootstrap Loader |
Responsible for loading system classes (Jre/lib/rt.jar classes) |
Extended class |
Extclassloader |
Responsible for loading extension classes (Jar/lib/ext/*.jar classes) |
Custom class |
Appclassloader |
Responsible for loading the application class (Classpath specified directory or jar class) |
implementation principle: through the way of the delegate, when a class needs to be loaded, the class loader requests the parent class to complete the load, and the parent uses its own search-road strength to search for the class that needs to be loaded, and if the search does not, the subclass searches for the class to load according to its search path
the main steps of class loading:
1, load: According to find the path to find the corresponding class file, and then import
2, Link:
2-1, check: Check the correctness of the class file to be loaded
2-2. Preparation: Allocate storage space to static variables in a class
2-3. Parsing: Converting symbolic references to direct references (optional)
3. Initialization: Perform initialization work on static variables and static code blocks 9, garbage collection (GC)
Garbage collection is mainly the memory that is no longer used in the Recycle program, which mainly completes 3 tasks: allocating memory to ensure that the memory of the referenced object is not incorrectly reclaimed the memory space of the object that is no longer referenced
Garbage collection increases productivity, guarantees degree of stability, the garbage collector must track memory usage, release unused objects, complete memory release to deal with fragmentation in the heap, and these operations increase the burden of the JVM, thereby reducing the execution efficiency of the program The garbage and the collector records and manages all objects in the heap memory using a forward diagram
garbage Collection Algorithm : Reference counting algorithm: In the heap for each reference has a reference counter, can not solve the problem of mutual reference tracking recovery algorithm: Maintenance of an object reference map, starting from the root node traversal, while marking the traversal to the end of the traversal, unmarked objects will be recycled Compression recovery algorithm: moving objects in the heap to one end of the heap at the same time, the fragments in the heap are sorted, although the action to eliminate fragmentation is simplified, but each operation is a large performance loss replication recovery algorithm: The heap is divided into 2 areas of the same size, at any time only one of the areas is used until the entire area is used up , the garbage collector interrupts program execution, by traversing all the active objects to another area, the replication process is close together, eliminating memory fragmentation, the program continues to run after the end, and repeats the process on a per-generation basis: the copy-and-Recycle algorithm all active objects are replicated each time they are executed. inefficient; Divide the heap into many sub-heaps, each of which is considered a generation, in which the algorithm prioritizes young objects in the process of running, and if an object is still alive after multiple collections, move the object to the advanced heap, reducing the number of scans 10, memory leaks
A memory leak is an object or variable that is no longer being used by a program and holds storage space in memory.
there are 2 criteria for determining whether a single memory space is eligible for garbage collection in Java: assigning empty null to an object, and then reallocating the memory space after it has not been used to give the object a new value
There are 2 common memory leaks: The space requested in the heap is no longer in use, but remains in memory
Causes of memory leaks: Static collection classes (these classes create a container lifecycle as long as the program, and the objects in the container end up not being freed) a variety of connections (the connection is not closed, causing a large number of objects to be recycled) listeners (listeners are not removed when the object is disposed) The irrational scope of a variable (the scope of a variable definition is greater than the scope of use) a single case pattern can result in a memory leak (a reference to an object exists in a single case pattern, a single case pattern life cycle is the same as a program, so the object reference cannot be freed) 11
In Java, heaps and stacks are places where data is stored in memory.
Memory |
Store Things |
Memory Management Mode |
Stack |
Variables (base data types and reference types) variables out of scope are automatically released |
Pressure stack and stack, to stack frame as the basic unit Management program call relations, there are function calls will also be pressed into the stack |
Heap |
Object referencing a type variable, created by a method such as new |
Object created at run time, garbage collector reclaims |
Constant pool |
such as String objects, created by methods such as new |
Object created at run time, garbage collector reclaims |
The JVM is a stack based virtual machine, with each Java program running on a separate JVM instance, with each instance uniquely corresponding to a heap, and multiple threads within a Java program running on the same JVM instance, which share heap memory (synchronized when multithreaded scope heap data)
After an array or object has been generated in the heap, you can define a special variable in the stack, when the value of this variable in the stack, such as an array or object in the heap memory of the first address, the stack of this variable becomes an array or object reference variable (reference variable is equivalent to a group or object of a name, You can then use the stack reference variable in your program to access the array or object in the heap.
The main storage object in the heap, the stack is mainly used to execute the program
The stack's access speed is fast, but the size and lifetime of the stack must be fixed and inflexible
You can dynamically allocate memory at run time without telling the compiler in advance, but with slow access