Server: Tomcat support servlet JSP JBoss Open source application Server Apache: Most extensive HTTP server, only static Web page supported
String is the length immutable, a new string object is generated with + =, StringBuffer and StringBuilder are variable lengths, StringBuffer is thread-safe
Concurrent programming: The objective ordering of atomicity
Serializable: Static cannot be serialized, and transient-modified cannot be serialized
Process-oriented and object-oriented:
Process-oriented: fast, efficient maintenance, difficult to expand, difficult to take
Object-oriented: slower than process-oriented, but easy to maintain, easy to expand, easy to reuse
The difference between JDK and JRE: the bin under the JDK has the Javac JRE under the bin without
Basic data type Why can't I use = = when I'm judging equality? Answer: Storage accuracy problem, general use threshold, A-B is less than this threshold, generally considered equal.
Parallel: Two or more events occur at the same time. Concurrency: Two or more events occur at the same time interval.
object does not implement the Callable method if the object call throws an exception
The subclass and parent class have the same name, but can be overridden in a subclass, but super calls
A corresponds to an ASCII code of 65 0 for 45
If a local variable is not assigned an initial value is not callable
Process basic state: County seat: A separate running unit that is smaller than the process and can have multiple threads executing concurrently in the same process. Thread: The basic unit of CPU dispatch. Process: The basic unit of CPU allocation resources.
Integer.parseint (S,x) s represents the converted number, and x represents the conversion to how many binary
If the try,finally has a retrun statement, the return in the try is ignored
Inner class
member Inner class
Local inner class
Static Inner class
Anonymous inner Class (inherits a method or implements an interface)
Members of an external class cannot access members of an inner class (except for static inner classes) the inner class can access all members of the outer class.
Port number to differentiate processes
Java Reflection
- You can get information about a class at run time
StringBuffer Bottom is char[] expansion of an expansion of twice times +2 (left shift 1)
There will only be one string object with the same value in the constant pool
Local variables have no default values and must be assigned manually
The Java interface modifier can only be abstract and public
The difference between error and exception
The Error class generally refers to the exception of a virtual machine, and for this exception, the program itself cannot be recovered and prevented
Exceptio represents an exception that a program can handle, that is, an exception that occurs when a program writes an error.
Final initialization has only two local definitions and constructors
Output two-digit System.out.print ("%.2f", CC);
Java Sync Lock
Each object has a lock on its own, monitor lock, monitor is a thread-private data structure, each thread has a list of available monitor record, and there is a globally available list, each locked object will be associated with monitor, There is an owner field in Monitor that holds the unique identity of the thread that owns the object, indicating that the lock is occupied by this thread,
Lock coarsening: Connect multiple lock operations together to form a larger range of locks
Java8 new Features:
HashMap initialization does not initialize the array, but rather initializes the array at the time of the put operation
TreeSet: Implements the CompareTo method, defines a class, implements the Conparator, the bottom implementation is the Red black tree
Hashset:hashcode different must not be the same element, the same is the same as the bottom of the equals two fork tree
Collection has iterator so the set and list have maps that need to be entryset and keyset
HashSet is not thread safe
The head of the priority queue is the smallest element determined by the order of the specified rules
TreeMap Sort by the natural order of the keys
The time complexity of the hash lookup is independent of the original quantity, when the hash table looks for the element, it is directly by calculating the hash value to determine the position of the element, thus directly accessing the element, the insertion of the hash table, the deletion, the search is O (1)
Blocking queues:
Linklist is the implementation of the queue
HashSet is based on the HASHMAP implementation, allowing NULL to not allow for repetition,
Concurrenthashmap: Thread-safe hashmap, do not need to lock when get, put must lock
Concurrentmap Allow iteration over updates
Each thread shares process resources and can be scheduled independently, and threads are the basic unit of CPU scheduling
Race Condition:
- A different result due to improper execution order, based on a possible failure of observation results to make judgments.
The status of the thread pool
Was in running state when it was first created.
After calling the shutdown method, it belongs to the shutdown state, and the new thread is not accepted at this time, waiting for the existing thread task to complete.
After calling the Shutdownnow method, it enters the stop state, does not accept the new thread at this time, and attempts to terminate the executing thread
The thread pool enters terminated when the task cache queue is emptied when in shutdown or stop state and all threads have been destroyed
Synchronized VS Lock
L is an interface, S is a keyword
S will automatically release the object lock when an exception occurs, L will not release the lock if there is no unlock, so unlock should be placed in finally
By L can know whether to obtain the lock successfully, S can not
L can improve the efficiency of reading and writing for multiple threads
Threadloacl:threadlocal provides a separate copy of the variable for each thread that uses the variable, so each thread can independently change its own copy without affecting the copy of the other thread. THREADLOCL uses a hash table to provide a copy of each thread
There is a map in the class that stores a copy of each thread variable, and the map key is the Threadlocal object, and value is the thread copy of the variable.
The key is in the Threadlocalmap class, which is the static inner class of threadlocal, which implements the setting and acquisition of key-value pairs. Each thread corresponds to a threadlocalmap, which implements the isolation of variable access in different threads. Because the variables are unique to each thread, there is no concurrency error at all.
Fair lock
- Multiple threads are allocated according to the order in which they are requested for a lock, synchronized is not a fair lock
Spin lock
- When two or more than two threads execute in parallel, we can let the next thread wait a little bit, but do not discard the processor execution time, see if the thread holding the lock releases the lock quickly, in order for the thread to wait, we need to have the thread perform a busy loop, which is the spin lock.
Synchronized: Synchronous code block and synchronous method, synchronous method Object lock is the class object of this static method
After compiling the Synchronized keyword, the moniterenter and moniterexit Two bytecode instructions are formed before and after the synchronization code block, and the two bytecode parameters require a reference type parameter indicating the object to lock and unlock. In the execution of the moniterenter instruction, the first attempt to obtain the object's lock, if the object has not been locked, or the current thread corresponding already owns the lock object, the lock counter +1, corresponding to the execution of Moniterexit will lock the counter-1, when the counter is zero, the lock is released.
Java Virtual machines can acc_aynchronized flag bits from the method table to know if a method is a synchronous method, and when a method is synchronous, the thread requires that the Moniter be successfully held before executing the method
Multithreading problem: When multiple threads are manipulating a thread to share statements, one thread executes only part of the statement, does not finish, and another thread participates in execution, causing the error of shared data, the workaround: Thread synchronization
Reentrantlock: Can re-enter the lock, that is, the thread that now occupies the lock can be repeatedly entered, but must be repeated exit, 2. Can be interrupted, 3. The time to acquire the lock can be set, the lock is not acquired within the specified time, and a failure is returned, which does not constitute a deadlock 4. Fair Lock: First come first served
Shared Lock: Allows multiple threads to enter the critical section at the same time, but the share limit is limited, when the quota is used up other threads or blocked, when the quota of 1 is equivalent to lock
Readwritelock: Read-write lock, reading-read not mutually exclusive, read-write mutex, write-write also mutually exclusive
The thread task in the thread pool is to constantly check that the task queue has a queue and continuously execute the tasks in the queue
Sleep Wait
Sleep is a method of threading and wait is a method of the object class, and sleep only frees the CPU for execution
Sleep does not release object locks and wait releases object locks
Sleep automatically returns to the ready state after a specified time, and wait needs to wake up
Synchronization: When a call is made, waits for the result to be called before the result is obtained, blocking the current program
Asynchronous: The call returns immediately after the issue, not waiting for the result to be called, but the caller is notified through the status after the result is made,
Blocking: When the result is not returned before the front end is suspended, know until the result is returned
Non-blocking: The call does not block the current thread until the result is immediately available.
BIO: Synchronous blocking
NIO: Synchronous non-blocking
AIO: Asynchronous non-blocking
Newio is a new IO
IO: Flow-oriented, blocking, no selector; NIO: buffer-oriented, non-blocking IO, selective;
Nio:nio is more efficient than IO, NIO is facing the cache while IO is directly facing the stream, NiO is non-clogging while IO is clogging
Channel: The destination of any source needs to pass through a channel object, a buffer is a container object, the data sent to Channer must first be placed in buffer, the data read from the channel must be put in buffer
Read and write data using buffer: 1. Write data to Buffer 2. Call Filp Method 3. Reads data from buffer 4. Call the clear and compact methods
When you want to write data in buffer, buffer will record how many lines are written, the read data will need to clear the buffer, so that he can be written again, there are two ways to clear the buffer, 1. Clear clears all buffers 2. Compact clears data that has already been read
Channel type
FileChannel: Reading data from a file
Datagramchannel: Read and write UDP network protocol data.
Socketchannel: Read and write TCP network protocol data.
Serversocketchannel: Can listen for TCP connections.
- The
-
File reading section requires three steps: Get Channer from FileInputStream, create buffer to read data from buffer
public static void main (string[] args) throws IOException {FileInputStream FileInputStream = new FileInputStream (New File ("Demo1.java")); FileChannel channel = Fileinputstream.getchannel (); Bytebuffer buffer = bytebuffer.allocate (1024); FileOutputStream FileOutputStream = new FileOutputStream (New File ("Demo2")); FileChannel Outchannel = Fileoutputstream.getchannel (); int len = 0; Long size = 0; while (len = channel.read (buffer))! =-1) {size = size + len; Buffer.flip (); Outchannel.write (buffer); Buffer.clear (); } System.out.println (size/1024.0); Fileinputstream.close (); Fileoutputstream.close (); Channel.close (); Outchannel.close (); }
Selector is an object that can register to multiple channel, listen to what happens on each channel, and can determine the channel's read and write according to the matter, so that multiple channel can be managed through one thread, processing a large number of network connections
Selector can only manage asynchronous Channel,socketchannelSelectionKey key = channel2.register(selector, SelectionKey.OP_READ);
- Second parameter: The channel triggers an event that is ready for the selected parameter 1. Connect with connect 2. Ready to receive data from accept 3. Data readable read 4. Data writable write can register multiple events,
Int interest=SelectionKey.OP_READ|SelectionKey.OP_ACCEPT
When one or more channels are registered on the selector, you can call an overloaded method to return events of interest to youselector.select(SelectionKey.OP_ACCEPT);
int select (): blocks to at least one channel ready for events that you register; int select (Long timeout): As with select (), only the longest will block timeout Ms;int Selectnow (), not block, No matter what channel is ready to return immediately, if no channel becomes optional since the previous selection operation, return 0 directly.
The servlet declaration cycle, which initializes the servlet when the Web container is initialized or the first time it accesses the servlet, calls the constructor method and Init, and when the servlet is requested, calls that method by Doserivice. Call the Destory method when the servlet destroys
Cookies are placed on the client
The cookie is session-level, stored in the browser, and you want to save the cookie as the maximum time to survive the cookie.
A cookie is a workaround for the client to maintain HTTP status, and the Session is a workaround for the server to maintain HTTP status
Session
A sessionid that corresponds to a session
When a session is created, the SessionID is placed in a cookie to be transmitted, and the next time the browser accesses the SessionID, the browser will know the current user session (also can be transmitted via a URL)
Close the browser will only invalidate the client session, the server will not (but the server session has the maximum survival time)
Application of Filter:
Disables the browser's cache.
Character encoding filter. If there is no filter, write request.setcharacterencoding on each request page,
Filter that detects whether the user is logged on.
ForWord and redirect
Is the server requests the resources, the server directly accesses the URL of the destination address, reads the URL corresponding content, then sends to the browser, the browser does not know where the server sends the content to obtain from, therefore the address bar still is the original address
Redirect is to allow the browser to access the address, so the address bar will change, equivalent to two request and response
Forward forwarded pages and forwarded to the page can share data redirect cannot
Forward can only be forwarded between Web apps, redirect may navigate to other resources on the same site
Forward/Represents the Web App root directory, Redirect/represents the top root directory of the stack
JSP nine large built-in objects
Request
Session
Appication
PageContext
Request
Out
Page
Config
exception
JSP actions
Jsp:include: Contains
Jsp:userbean: Finding or instantiating a bean
Jsp:setproperty: Passing Parameters
Jsp:forward Request Forwarding
How do I implement servlet single-threaded mode? Answer: To implement single-threaded mode, you can modify the IsThreadSafe property in the configuration file, for example, <% @page isthreadsafe= "false"%>
Static inclusions, two JSP pages are included before compilation, and a servlet is generated at the end
Dynamic inclusion: First parsing two JSP pages into servlet integration
The problem of Hiberante 1+n
One-to-many: in 1 of the query to the object, due to the existence of the association, it is necessary to extract n associated objects, because the number of sets of n also to send n SQL so altogether send n+1
Many-to-one: many of the parties query to n objects, issued an n statement, because n objects associated with an object so you want to send another statement, so N+1
Iterator: The query will go to the cache first and then, if not, go to the database for n+1
Hibernate Load and get differences
If no object is queried, get returns NULL, and load throws an exception
Load returns the entity's proxy class, and get returns the entity class
Load can use the level two cache to query the data, and get can only be used in the internal cache, if the internal cache does not skip the level two cache directly querying the database
When we load an object with Session.load, we do not generate the SQL statement, we get only a proxy object, and when we use the other fields, we send the query statement, Session.get No matter whether we use this object will send the SQL statement
If there is a class load request, first check whether it has been loaded, if not loaded, call the parent class Loader's LoadClass method, if the parent class loader is empty, the default is to use the Startup class loader as the parent ClassLoader, if the parent class loader fails, throws an exception, Then call your own Findclass method to load
Class initialization order: Load class file, static variable initialization (subclass and parent class executed in order of occurrence) parent class variable, parent class constructs code block, parent class constructor, subclass variable, subclass constructs code block, subclass constructor
The process of Java compilation
When the JVM starts loading classes
Run Bootstarp ClassLoader load the core API, then perform ext classLoader load extension API, and finally the app ClassLoader load classpath directory of class, the most basic process.
The class is not parsed or initialized by ClassLoader when the class is loaded, and the Forname method parses and initializes class
JVM parameters
XMX: Maximum Heap Size
Xms: Minimum heap size
XMN: Young generation Heap Size
XSS: The size of the heap
Xxsurvivoratio: Comparison of the size of Eden and Survivo districts in the younger generation
The loading process of the class
Class Loader:
Memory leaks, objects are accessible, objects are not used in the future
Memory overflow (there is not enough memory allocation when the program requests memory)
Java virtual machine opcode has only one byte
The target referenced by the symbol does not necessarily include memory, and the target directly referenced must be in memory
Garbage collection
GCRoot: Through a series of GCRoot objects as the starting point, starting from these nodes down search, traversed by the path is a reference chain, when an object to GCRoot does not have a reference chain, then the collection, if the object does not have a reference chain connection, then it will be marked and filtered, If the object has a rewrite Finalize method or has been called, it will be destroyed, if necessary to execute the Finalize method, the object will be placed in the F-queue queue, the second token, if they are connected to an object during this period, it will not be recycled
GCRoot:
Objects referenced in the Java Virtual machine stack
Object referenced by static property of class in method area
Objects referenced by constants in the method area
Local method Stack Jni referenced object (JNI calls other languages such as c,c++ usage native)
Stop-Copy algorithm:
- Divide the memory into equal two blocks each time you use one of them, recycle the garbage and put the surviving object on top of the other piece, then clean up the piece (inefficient, resulting in memory fragmentation)
Striped Collection
Divided into young bands (EDEN,SURVIVO1,SURVIVO2), the old age (tenured)
The first object is placed in the Eden Zone, and when the new object is generated and the Eden request space fails, the minor GC is triggered, GC is performed on the Eden Zone, the non-surviving objects are cleared, the surviving objects are moved to Survivo1, and the Survivo two memory areas are organized. The GC here does not affect the old age, so the GC in the Eden area will be frequent. Therefore, it is generally necessary to use fast and efficient algorithms, so that the Eden area can be free as soon as possible. At the same time, each object has an age, that is, the number of times experienced minor GC, when an object's age to a certain limit when the object will be moved to the old age area, when the old area of space is not the time will trigger the old area of garbage collection treatment
Common allocation methods for garbage collection: pointer collisions, idle lists
The contents of the class file
The first 4 of each class file itself to identify whether it can be accepted by the virtual machine
Then the version number (5 6 bytes is the minor version number 7 8 is the main version)
Then the main version number is the entry of the constant pool.
Access flags
Index (class index, parent class index, interface index)
Field table
Method table
property sheet
How TCP guarantees Reliability
Splitting data into chunks that TCP thinks fit to send
Time-out retransmission: When TCP sends a data segment, a timer is started, waiting for the destination to confirm that the message is received, and if it cannot receive a confirmation in time, a message segment will be sent again.
When TCP receives a message segment, it sends a confirmation to the other, which is usually not sent immediately, and is usually delayed by a few 1 seconds.
When TCP receives a message segment but the message segment has an error, it discards the message segment and does not give a response
Reorder data and then hand it over to the application layer
For duplicate data, discard directly
TCP can control the flow of the host faster to prevent the transmission of data too fast cause the host slower side buffer overflow
BYTE Stream Service
- Two applications are connected by byte stream, TCP does not insert a record identifier in a byte stream
TCP and UDP--TCP: connection-oriented, providing reliable service, no duplication, no loss, no error, byte stream oriented, only point-to-point, header 20-byte, full-duplex. UDP: No connection, maximum effort delivery, message-oriented, support for a pair of one or one-to-many, many-to-many, header 8-byte
HTTPS:HTTP+SSL/TLS, added a layer of encryption information on the HTTP module, the service side and the client's transmission will be encrypted.
The client makes an HTTPS request
Server-side configuration
Transfer Certificate
Client resolution certificate (generates a random value and encrypts it with the public key)
Transmit encrypted information (transmitted as a random value after encryption)
Server-side decryption information (resolved by symmetric encryption of the algorithm passed the request)
The corresponding transport encryption
Client decryption (client-side catch is clear)
Reverse Proxy and forward proxy
Forward proxy: Connect a proxy server let him help us visit the target site, the target site does not know who the client is,
Access to sites not accessible
Can speed access to resources
Hide customer information from outside
Reverse proxy: When the client requests the server, it does not know where the data returned by the server comes from, and the agent distributes the request to a different server
Load Balancing
Ensure intranet security
Five ways to set up reverse proxy in Nginx
Polling (default), each request is assigned to a different backend server in chronological order, and can be automatically rejected if the backend server is down;
Specifies the weight, specifying the polling chance. The larger the weight, the greater the chance of polling for the uneven performance of the backend server.
IP binding Ip_path, each request is allocated according to the hash result of the access IP, so that each client fixed access to a server, can solve the session problem.
Fair (third-party) assigns requests in response time to the backend server, with a short response time priority allocation.
Url_hash assigns requests by accessing the URL results so that each URL is positioned to the same back-end server.
WebService: is a cross-programming language and remote call technology across the operating system, that is, the server is written in Java, the client program can be written in other programming languages, and the client and server programs can be run on different operating systems.