Java Fundamentals (ii)

Source: Internet
Author: User
Tags stub throwable try catch concurrentmodificationexception

1, string
New String ("ABC") has created several objects?
One or two, if there is an "ABC" in the constant pool, only one object is created and two objects are created if there is no string "abc" in the Constant pool.

String s="abc";String s1="ab"+"c"true ,因为"ab"+"c"在编译器就被转换为"abc",存放在常量区,因此输出结果为true。

2,java defines a base class (Java.lang.Throwable) as the parent class for all exceptions. Error, Exception, and RuntimeException are all subclasses of the throwable, so they can be thrown using throw.

In Java, common Runtime Exceptions (runtime exception) are: NullPointerException, classcastexception, ArrayIndexOutOfBoundsException, Arraystoreexception, Bufferoverflowexception, ArithmeticException, etc...
Run-time exceptions cannot be captured with try catch.

The main function of 3,java IO stream is to improve program performance and ease of use.
divides into byte stream and character stream.
The byte stream, in bytes (8bit), contains two abstract classes: the InputStream input stream and the OutputStream output stream.
Character streams, in characters (16bit), can read multiple bytes at a time and contain two abstract classes: Reader input stream and writer output stream.
The main difference between a byte stream and a character stream is that the byte stream does not use the cache when it processes the input and output, and the character stream uses the cache.

The Java IO class uses the Decorator (decorator) mode at design time.

The difference between 4,nio (nonblocking io) and IO
The first major difference between Java NiO and Io is that IO is stream-oriented and NIO is buffer-oriented. The Java io-oriented stream means that one or more bytes are read from the stream every time, until all bytes are read, and they are not being slowed anywhere. In addition, it cannot move data in the stream back and forth. If you need to move the data read from the stream before and after it, you need to cache it to a buffer first. Java NiO has a slightly different buffer-oriented approach. The data is read to a buffer that it processes later, and can be moved back and forth in the buffer if needed. This increases the flexibility of the process. However, you also need to check if the buffer contains all the data that you need to process. Also, make sure that when more data is read into the buffer, do not overwrite the data that has not been processed in the buffer.

Blocking and non-blocking IO

The various streams of Java Io are blocked. This means that when a thread calls read () or write (), the thread is blocked until some data is read, or the data is fully written. The thread can no longer do anything during this time. The non-blocking mode of Java NIO enables a thread to send requests to read data from a channel, but it can only get the data that is currently available and will not get anything if no data is available. Instead of keeping the thread blocked, the thread can continue to do other things until the data becomes readable. The same is true for non-blocking writes. A thread requests to write some data to a channel, but does not have to wait for it to be fully written, and the thread can do something else at the same time. Threads typically use non-blocking IO idle time to perform IO operations on other channels, so a single thread can now manage multiple input and output channels (channel).

Selector (selectors)

The Java NiO selector allows a single thread to monitor multiple input channels, you can register multiple channels using a selector, and then use a separate thread to "select" the channel: these channels already have inputs that can be processed, or select the channels that are ready to be written. This selection mechanism makes it easy for a single thread to manage multiple channels.

5,socket Communication
Common Pen Questions

Open the ServerSocket connection, accept accepts the connection read read data send sends data close connection server side: PackageJava basics. Socket;ImportJava.io.BufferedReader;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.ServerSocket;ImportJava.net.Socket;Importjava.util.*; Public  class Server {     Public Static void Main(string[] args) {//TODO auto-generated method stubBufferedReader br=NULL; PrintWriter pw=NULL;Try{ServerSocket server=NewServerSocket ( -); Socket socket=server.accept ();//Get input streamBR =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ()));//Get output streamPW =NewPrintWriter (Socket.getoutputstream (),true); String S=br.readline ();//Get received dataPw.println (s);//Send the same data to the client}Catch(Exception e)        {E.printstacktrace (); }finally{Try{Br.close ();            Pw.close (); }Catch(Exception e)            {E.printstacktrace (); }}} Client: PackageJava basics. Socket;ImportJava.io.BufferedReader;ImportJava.io.InputStreamReader;ImportJava.io.PrintWriter;ImportJava.net.Socket;Importjava.util.*; Public  class Client {     Public Static void Main(string[] args) {//TODO auto-generated method stubBufferedReader br=NULL; PrintWriter pw=NULL;Try{Socket socket=NewSocket ("localhost", -);//Get input stream and output streamBr=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); pw=NewPrintWriter (Socket.getoutputstream (),true);//Send data to the serverPw.println ("Hello"); String s=NULL; while(true) {s=br.readline ();if(s!=NULL){ Break;        }} System.out.println (s); }Catch(Exception e)        {E.printstacktrace (); }finally{Try{Br.close ();            Pw.close (); }Catch(Exception e)            {E.printstacktrace (); }        }    }}

Before the advent of non-blocking IO (NIO), Java implemented basic network communication functions through a traditional socket.

NiO uses polling to handle multi-threaded requests without context switching , and multi-threaded implementation requires context switching when switching between threads, and also requires the operation of stack and stack, so NIO has higher execution efficiency.
And the NIO uses buffer to save data (such as Bytebuffer, Charbuffer, etc.), simplifying the management of convective data.

NiO plays a very important role in network programming, and because NIO uses a non-blocking approach compared to traditional sockets, NIO is much more efficient than the socket when it comes to processing large numbers of concurrent requests.

Serialization of 6,java

Two ways: Implement Serializable interface (WriteObject, ReadObject), Externalizable (writeexternal, readexternal)

data members declared as static or transient cannot be serialized. that is, Java does not instantiate variables that are modified by static or transient when serializing
Because: Static represents a member of a class, transient (transparent, if an instance variable is declared with transient, when the object is stored, its value does not need to be maintained, representing the object's temporary data).

When to serialize (convert an object to a stream for ease of transmission):
1) The object needs to be sent over the network, or the state of the object needs to be persisted into the database or file.
2) serialization enables deep replication and can be used to copy referenced objects.

 PackageBasic Java knowledge;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;Importjava.io.Serializable;Importjava.util.*; Public  Class serialization implements Serializable{    PrivateString name;Private intAge PublicSerialization () { This. name=name; This. age=age; } PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; } Public Static void Main(string[] args) {//TODO auto-generated method stubSerialization of p=Newserialization (); ObjectOutputStream oos=NULL; ObjectInputStream ois=NULL;Try{FileOutputStream fos=NewFileOutputStream ("Perple.out"); oos=NewObjectOutputStream (FOS);            Oos.writeobject (P);        Oos.close (); }Catch(Exception e) {Serialization of P1;Try{FileInputStream fis=NewFileInputStream ("Perple.out"); ois=NewObjectInputStream (FIS);                p1= (serialized) Ois.readobject (); System.out.println ("Name:"+p1.getname ()); System.out.println ("Age:"+p1.getage ());            Ois.close (); }Catch(Exception ex)            {Ex.printstacktrace (); }        }    }}

Deserialization (Will flow to object)

A Java program runs from top to bottom in order of the Environment:
Java programs, JRE/JVM, operating systems, hardware.

The Java file is compiled by the JAVAC directive into a bytecode file of the. class suffix, which is then executed by the JVM. The Java program will generate bytecode after compiling the code.

Class loading steps:
1) load. Locate the corresponding class file, and then import the
2) Check the correctness of the class file to be loaded.
3) Prepare. Allocates storage space for static variables in a class.
4) parsing. Converts a symbolic reference to a direct reference.
5) Initialize. Perform initialization work on static variables and static blocks of code.

7, garbage collection (GC garbage Collection)

The memory that is no longer used in the Recycle program.

The garbage collector is responsible for completing 3 tasks: allocating memory, ensuring that the referenced object's memory is not being reclaimed incorrectly, and reclaiming the memory space of objects that are no longer referenced.
As long as more than one variable references the object, the object is not recycled.

Garbage collector, which uses a graph to record and manage all objects in memory, through a map to identify which objects are "accessible" (the variable refers to it as "unreachable"), and All "unreachable" objects are garbage-collected.

Garbage collection algorithm:
1) Reference counting algorithm: Low efficiency, the JVM is not used.
2) Tracking Recovery algorithm
3) Compression Recovery algorithm
4) Replication Recovery algorithm
5) recycling algorithm by generation

Can I proactively notify the JVM to do garbage collection?
The garbage collector cannot be called in real time to garbage collection of an object or all objects. The System.GC () method can be used to "notify" the garbage collector to run, of course, the JVM does not guarantee that the garbage collector will run immediately.

8, Memory leak
There are two cases: one, the space requested in the heap is not released:
Second, the object is no longer in use and still remains in memory. Memory leaks in Java are primarily the second case.

Causes of memory leaks:
1) Static Collection class. such as HashMap, Vector. Their lifecycle is consistent with the program, and objects in the container cannot be freed until the program ends, causing a memory leak.
2) Various connections, such as database connection, network connection and IO connection. When you are no longer in use, you need to call the Close method to release the connection to the database.
3) Listener
4) The scope of the variable is unreasonable.

9, container
Collection:set, List
Map

1) The set interface has two implementation classes: HashSet, TreeSet (implements the SortedSet interface, the elements in the TreeSet container are ordered)
2) List interface implementation class: LinkedList, ArrayList, Vector
3) The implementation class of the Map interface: HashMap, TreeMap, Linkedhashmap, Weakhashmap, Identityhashmap.
HashMap is based on the implementation of the hash list, using the object's hashcode can be quickly queried. The Linkedhashmap takes a list to maintain the internal order. TreeMap is based on the data structure of the red-black tree, and the inner elements are arranged on demand.

10, iterator
1) Use the container's iterator iterator () method to return a iterator, and then return to the first element through the next () method of iterator.
2) Use Iterator's Hasnext () method to determine if there are elements in the container, and if so, use the next () method to get the next element.
3) The element returned by the iterator can be removed through the Remove () method.

You often encounter concurrentmodificationexception exceptions when using the iterator () method, which is usually caused by operations that use iterator to traverse the container while adding or removing the container, or because of a multithreaded operation.

Single-threaded solution: During traversal, save the objects that need to be deleted into a collection, and then call the RemoveAll () method to delete them after the traversal is over, or use the Iter.remove () method.
Multithreading workaround: Use a thread-safe container instead of a non-thread-safe container, such as Concurrenthashmap, Copyonwritearraylist, and so on, or you can put the operation of the container into the synchronized code block,

The difference between Iterator and Listiterator:
Iterator can only traverse the collection in a forward direction, and is suitable for fetching and removing elements. Listiterator inherits from Iterator, specifically for list, and can traverse the list in two directions while supporting element modifications.

The difference between ArrayList, Vector and LinkedList
ArrayList, Vector:
Supports the use of subscripts to access elements, while indexing data faster, but the insertion of deleted elements need to move elements, the execution is relatively slow. ArrayList, Vector has an initialized capacity, vector each default expansion to the original twice times, ArrayList default expansion of the original 1.5 times times.

The difference is that vectors are thread-safe and ArrayList are thread-insecure,
LinkedList is implemented with two-way linked lists, with high efficiency and non-thread-safe insertion and deletion.

The difference between 12,hashmap, HashTable and Concurrenthashmap:
Concurrenthashmap is also a hash-based map, but it uses a completely different locking strategy to provide higher concurrency and scalability.

Instead of synchronizing each method in the same lock and allowing only one thread to access the container at a time, Concurrenthashmap uses a finer-grained locking mechanism to achieve greater sharing, a mechanism called segmented locks, in which Any number of read threads can access the map concurrently, and the thread that performs the read operation and the thread that performs the write operation can access the map concurrently.

The result of Concurrenthashmap is that higher throughput will be achieved in the context of concurrent access, while only minimal performance is lost in a single-threaded environment. The concurrentmodificationexception is not thrown, so you do not need to lock the container during the iteration. The map is not implemented in CONCURRENTHASHMAP to provide exclusive access. In Hashtable and Synchronizedmap, obtaining a map lock prevents other threads from accessing the map,

In most cases, concurrenthashmap to replace synchronous map can further improve the scalability of the code, only if the application needs to lock the map for exclusive access, you should discard the use of concurrenthashmap.

1, try to declare the domain as the final type, unless you want them to be mutable.
2, immutable objects must be thread-safe.

Immutable objects can greatly reduce the complexity of concurrent programming, they are simpler and more secure, can be freely shared without the use of locking or protective replication mechanisms.

3, use locks to protect each variable variable.
4, the same lock is used when all variables in the same invariant condition are protected.
5, if there is no synchronization mechanism when accessing the same mutable variable from multiple threads, there is a problem with the program.

Map deal with conflict methods: Open address method, hash method, chain address method, etc.
HashMap uses the chain address method to resolve conflicts,
To find value by key from HashMap, first call the Key's Hashcode () method to obtain the hash value of the key corresponding to the H, determine the key for all the value of key storage of the first address, if H corresponding key value has multiple, then the program will then traverse all keys, By calling the Equals () method of key to determine whether the contents of the key are equal, the corresponding value is the correct result only if the Equals method returns a value of true.

The difference between Collection and collections
Collection is a collection interface, the main List and set, which provides a common interface method for basic operation of the collection object.

Collections is a wrapper class for the collection class. Provides a series of static methods that the collections class cannot instantiate.

Multithreading
1, the difference between threads and processes
4 states of a thread: run, ready, suspend, end.
A process can have multiple threads, sharing the program's memory space between threads (code snippets, data, heap space, and some process-level resources, such as open files), but each thread has its own stack space.
1) Use multithreading to reduce the response time of the program.
2) threads are less expensive to create and switch than processes, making it easy to share data.
3) Use multithreading to simplify the program structure, make the program easy to understand and maintain

2, the realization of multi-threading method;
1) inherit the thread class, the replication Run method
2) Implement Runnable interface, replication Run method

The difference between the 3,start () method and the Run () method
The system initiates a thread by invoking the start () method of the thread class, which can be truly multithreaded only by invoking the start () method of the thread class.

The way to set a user thread as a daemon is to call the Setdaemon (True) method of the object before calling the start () method. If the above parameter is set to False, the user process mode is indicated.

Join () Method: Let the thread that called the method execute the Run () method and then execute the code after the join method.

Java Fundamentals (ii)

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.