Frequently asked questions and partial answers in Java interview (2018)

Source: Internet
Author: User
Tags cas finally block object object semaphore thread class unique id mysql index

One: Java basics
1. Briefly describe the string object, StringBuffer, StringBuilder distinguish
The string is final, storing the data internally with a final type of char array, which is less efficient to splice, actually by creating a stringbuffer, letting the background call append (), and finally StringBuffer tosting () , each operation sting a new object to hold the new value. So the original object will be useless, it will be garbage collection. This is also to affect performance.
StringBuffer is also final, thread-safe, using a char array to hold the string that needs to be append, the char array has an initial size, and when the string length of append exceeds the current char array capacity, the char array is dynamically extended, That is, re-apply a larger memory space, and then copy the current char array to a new location, because the cost of reallocating memory and copying is relatively large, so each re-application of memory space is a request greater than the current need of memory space, here is twice times.
StringBuilder, thread is not secure.

2. The principle of polymorphism
Polymorphism is: Allows a pointer to a base class or reference to an object of a derived class, and implements dynamic binding of a method at specific accesses.
The principle is late binding for Java.

3. Briefly describe the idea of object-oriented programming
Abstraction: The process by which a particular instance extracts the concept formed after a common characteristic, which emphasizes the main characteristics and ignores the secondary characteristics.
Encapsulation: Combines the properties and methods of an object into an independent whole, hiding the implementation details and providing an interface for external access.
Inheritance: A new class, called a subclass, is derived from a known class. Subclasses implement all non-privatized properties and methods of the parent class.
And can expand the new behavior according to their actual needs.
Polymorphic: Multiple different objects respond to the same message, and the same message uses a variety of different behavior methods depending on the object.

4. Principle of Reflection
Java Virtual Runtime memory has a called method area, the main function is to store the type information of the loaded class. Each time a class is loaded, Java creates an instance of the class object. We can use this example to access the information for this class.

5. Role and implementation of agents
The role of proxy mode is to provide a proxy for other objects to control access to this object. In some cases, one customer does not want or cannot refer to another object directly, whereas a proxy object can act as an intermediary between the client and the target object.
Static proxy and dynamic proxy for Java (slightly)

Usage of 6.hashcode and equals
Java for the Eqauls method and the Hashcode method are defined as:
If two objects are the same, their hashcode values must be the same;
If the hashcode of two objects are the same, they are not necessarily the same (the objects mentioned above refer to the comparison using the Eqauls method.) )
It is common to overwrite the Equals () method while overwriting the Hashcode () method, otherwise it violates the General convention of Object.hashcode, which causes the class to fail with all hash-based (hash) collection classes (HashMap, HashSet and Hashtable) are combined to work properly.

7.set,map,list differences (as far as possible)
Map:
HashMap: Chain address method, approximate idea: By taking key hashcode value, high-level operation, modulo operation to calculate the position, The insertion position is determined by the Hascode and Eques methods to determine whether key is consistent with
①. Determines whether the key value of the array table[i] is empty or null, otherwise execute resize () to expand;
②. Calculates the hash value based on the key value key to get the inserted array index i, if table[i]==null, add directly to the new node, to ⑥, if table[i] is not empty, to ③;
③. Determine if the first element of Table[i] is the same as key If the same directly overrides value, otherwise to the ④, here the same refers to hashcode and equals,
④. Determine Table[i] is TreeNode, that is, Table[i] is a red black tree, if it is a red black tree, then directly in the tree insert key value pairs, Otherwise, turn to ⑤;
⑤. Traverse Table[i], to determine whether the chain table length is greater than 8, greater than 8 words to convert the linked list to a red-black tree, in the red-black tree to perform the insert operation, or the insertion of the linked list operation; If the key is found to have a direct overwrite value in the traversal process;
⑥. After the insert succeeds, determine whether the actual number of key values is greater than the maximum capacity threshold, if exceeded, for expansion. The
Treemap:treemap implements the SortedMap interface, which allows the records it saves to be sorted according to the key, by default the ascending sort of the key values, or by specifying a sort comparer, and when the treemap is traversed with iterator, the resulting records are sorted out. If you use a sorted mapping, we recommend that you use TreeMap. When using TreeMap, key must implement the comparable interface or pass in the custom comparator in the construction treemap, otherwise the Java.lang.ClassCastException type exception will be thrown at run time.
Linkedhashmap: The insertion Order of records is saved, and when traversing linkedhashmap with iterator, the first records must be inserted first, or they can be constructed with parameters, sorted by Access order.
HashTable: Because the internal is synchronized to ensure thread safety
Cocurrenthashmap: The number of locks is increased by using the lock segmentation technique, so that the number of threads vying for the same lock is controlled.

Set
HashSet: Internal New has a hashmap, add key to put data, value put an internally defined final object object
Linkedhashset: Inside New A linkhashmap, add key to put data, value put an internally defined final object object, traverse the orderly
TreeSet: Internal New has a treemap, add key to put data, value puts an internally defined final object object.
List
ArrayList and LinkedList (slightly)
Copywritelist:copyonwritearraylist suitable for use in scenes where read operations are far greater than write operations

8.
Integer demo1 = 100;
int demo2 = 100;

Integer Demo3 = 10000;
int Demo4 = 10000;

Integer demo5 = 100;
Integer DEMO6 = 100;

Integer Demo7 = 10000;
Integer Demo8 = 10000;

int demo10=10000;
int demo9=10000;
System.out.println (DEMO1==DEMO2);
System.out.println (DEMO3==DEMO4);
System.out.println (DEMO5==DEMO6);
System.out.println (DEMO7==DEMO8);
System.out.println (DEMO9==DEMO10);
Results:
True auto-unboxing boxing ratio size
True auto-unboxing boxing ratio size
True Java constant pool caches a reference
False two references
True than size

9. Rapid failure and security failure
Fast failures and security failures are for iterators. Fast failure: When iterating through a collection, if another thread is modifying this set, it throws a Concurrentmodification exception, and the Java.util is a quick failure. Security failure: A copy is made at the collection level two at iteration, so modifying the upper element of the collection does not affect the lower layer. It's safe to fail under Java.util.concurrent.

Two: Java multithreading
1. How to implement Multithreading
Inherit the thread class, overriding the Run method
Implement the Runnable interface, override the Run method, implement an instance object of the implementation class of the Runnable interface as the target of the thread constructor
Creating threads through callable and Futuretask
Creating threads from the thread pool

2. Multi-threaded status, flowchart

3. Thread pool
Threadpoolexecutor
Constructor method parameter explanation
parameter name Action
Corepoolsize queue is not full, maximum number of concurrent threads
Maximumpoolsizes The maximum number of concurrent threads that the thread can reach after the queue is full
KeepAliveTime how long the idle thread has been recycled
Unit keepalivetime time unit
WorkQueue blocked queue type
When Rejectedexecutionhandler exceeds maximumpoolsizes + workQueue, the task is given to Rejectedexecutionhandler to handle the
literal description
Corepoolsize , the relationship between Maximumpoolsize,workqueue.
When the thread pool threads are less than corepoolsize, the new commit task creates a new thread to perform the task, even if there are idle threads in the thread pool at this time.
When the thread pool threads reach Corepoolsize, the new commit task is put into Workqueue, waiting for the task to be scheduled to execute in the thread pool.
When Workqueue is full, and Maximumpoolsize > Corepoolsize, the new commit task creates a new thread to perform the task.
when Workqueue is full and the number of submitted tasks exceeds maximumpoolsize, the task is handled by Rejectedexecutionhandler.
These threads are reclaimed when the thread pool threads exceed corepoolsize and the idle time of this part reaches KeepAliveTime.
when Allowcorethreadtimeout (true) is set, the thread idle time in the Corepoolsize range of the thread pool reaches KeepAliveTime will also be reclaimed.

Newcachedthreadpool: Unlimited size thread pool. Reusing the available threads that were previously constructed, and if there are no available threads, re-creates a new thread and joins it into the thread pool. If the thread has not been used for more than 60 seconds, it will be aborted and removed from the cache. Therefore, the thread pool does not consume any resources after a long idle time.
Fixedthreadpool: Multiplexing a shared borderless queue with a fixed number of threads. At any point in time, a maximum of nthreads threads are active to perform the task. If more than one task is committed when all threads are active, it will wait in the queue until the thread is available. If any thread aborts during execution because of an error, the new thread replaces its location to perform subsequent tasks.
Singlethreadpool is an instance of Threadpoolexecutor created through Java.util.concurrent.Executors. This instance only uses a single worker thread to execute a borderless queue. (Note that if a single thread aborts during execution because some errors are aborted, the new thread overrides it to perform subsequent threads)

4. Multithreaded yield (), sleep (), wait (), join ()
The wait () and Notify/notifyall methods belong to the object method.
Wait (): The Wait method relies on synchronization, and the wait method needs to release the lock.
Yield (), sleep (), join () belongs to the thread class method.
Sleep (): can be called directly. The deeper difference is that the sleep method only temporarily yields the CPU's execution and does not release the lock.
Yield (): the effect of the yield method is to pause the current thread so that other threads have an opportunity to execute, but cannot specify a time to pause, and there is no guarantee that the current thread will stop immediately. The yield method simply transforms the running state into a runnable state
The Join:join method is to block the thread through the wait method, and if the join thread is still executing, block the current thread until the thread of the join completes and the current thread executes. However, it is important to note that the join here only calls the Wait method, but there is no corresponding notify method, because the thread's Start method does the corresponding processing, so when the join thread execution completes, will automatically wake up the main thread continues to execute

5.synchronized principle
Synchronized relies on the software-level JVM
Each object has a monitor lock. When monitor is occupied, it is locked, and the thread attempts to take ownership of the monitor while executing the monitorenter instruction, as follows:
1. If the monitor has an entry number of 0, the thread enters monitor and then sets the entry number to 1, which is the owner of the Monitor.
2, if the thread already occupies the monitor, just re-enter, then enter the monitor into the number plus 1.
3. If another thread has already occupied monitor, the thread goes into a blocking state until the number of incoming monitor is 0, and then tries to get ownership of monitor again.
Java SE1.6 introduces "biased lock" and "lightweight lock" to reduce the performance cost of acquiring locks and releasing locks.

6.lock principle
Lock independent of the JVM, depending on the hardware level,
The use of CLH to the column (what precursor, tail spin, not remember) implementation. The native CLH queue is used for spin locks, but Doug Lea transformed it into a blocking lock.

7.synchronized and Lock differences
Use on:
Synchronized when a function is successfully completed or throws an exception, the virtual opportunity automatically releases the lock that the thread occupies, and the lock object is held until the exception occurs, if the lock is not actively called by the Unlock () method. Therefore, lock must be released in the finally block when using lock;
Lock interface locks can be used in a variety of ways to try to acquire a lock including immediate return on whether the Trylock () is successful, as well as trying to obtain the lock () method and trying to wait for a specified length of time to obtain a method that is relatively flexible for many than synchronized;
Write locks improve the performance of the system because the read lock is a shared lock, that is, you can have multiple threads reading shared resources at the same time, while write locks guarantee that changes to shared resources can only be single-threaded.
Lock can achieve a fair lock

In principle: see above

8.JUC and contract the basic class
Atomic Atomic Category:
Atomic Update basic type (such as Atomicinteger): CAS operation to ensure atomicity of operations.
Atomic update array type (e.g. Atomiclongarray): CAS operation to ensure atomicity of operations.
Atomic update reference type (e.g. Atomicreference):

Concurrent Container classes:
Concurrenthashmap: Segmented lock mechanism guarantees concurrency
The disadvantage of copyonwritearraylist:copyonwritearraylist is that the cost of the modification is very expensive, and each modification is accompanied by an array copy at a time, but the advantages are also obvious, which is that there is no thread safety problem in concurrency. That is, absolute thread safety, similar to read-write separation and eventual consistency (data is not up-to-date)

Special Function Class:
Countdownlatch: (minus count mode) a counter is implemented, the initial value of the counter is the number of threads. Each time a thread finishes its task, the value of the counter is reduced by 1. When the counter value reaches 0 o'clock, it means that all the threads have completed the task, and then the thread waiting on the latch can resume the execution of the task.
Cyclicbarrier (plus count mode): Frees all waiting threads when the count reaches the specified value
Semaphore: Translated literally as a semaphore, Semaphore can control the number of simultaneous access threads, get a license through acquire (), and if not wait, release () releases a license.
ThreadLocal: Provide a separate copy of the variable for each thread

Lock class:
Reentrantlock (can be re-entered lock): can have a fair lock and unfair lock, try to obtain the lock (Trylock ()) and other advantages
The Condition:lock class can create Condition objects, Condition objects are used to thread wait and wake threads, and it is important to note that the Condition object wakes up the thread that executes the await method with the same Condition. So it's possible to implement a thread that wakes a specified class
Readwritelock: Read share, write mutually exclusive, read/write Mutex

Other:
Blockqueue: Synchronous implementation of queues

Thread Pool class:
See the introduction above.

9.blockQueue Blocking Queue

Class Boundedbuffer {
Final lock lock = new Reentrantlock ();
Final Condition notfull = Lock.newcondition ();
Final Condition notempty = Lock.newcondition ();

Final object[] items = new OBJECT[100];
int Putptr, takeptr, Count;

public void put (Object x) throws Interruptedexception {
Lock.lock ();
try {
while (count = = items.length)
Notfull.await ();
ITEMS[PUTPTR] = x;
if (++putptr = = items.length) putptr = 0;
++count;
Notempty.signal ();
} finally {
Lock.unlock ();
}
}

Public Object take () throws Interruptedexception {
Lock.lock ();
try {
while (count = = 0)
Notempty.await ();
Object x = items[takeptr];
if (++takeptr = = items.length) takeptr = 0;
--count;
Notfull.signal ();
return x;
} finally {
Lock.unlock ();
}
}
}

Three: Database (here mostly see MySQL InnoDB)
1.mysql Engine Category
MyISAM: Transaction not supported, table lock, foreign key not supported, nonclustered index, data file is separate, suitable for a large number of read applications
InnoDB: Support transactions, support foreign keys, table locks and row locks, clustered indexes, data files are tied to the index, must have a primary key, through the primary key index efficiency is very high. However, the secondary index requires two queries, first querying the primary key, and then querying the data through the primary key.
Other: NDB and memory (the data in the table is stored in RAM), Maria (the newly developed engine, designed primarily to replace the original MyISAM storage engine)

The difference between a 2.InnoDB table lock and a row and column lock
Table Lock: Slightly
Row Lock:
Two broad types: shared and exclusive locks
Shared Lock: Allows a transaction to read a row of data.
Exclusive lock: Allows a transaction to delete or update a piece of data.
A row lock is implemented by locking the index entry on the index.
Use: Because the InnoDB preset is Row-level lock, only the "explicit" specified primary key, MySQL will execute row lock (only to lock the selected data sample), otherwise MySQL will execute table lock (the entire data form to lock).

3.mysql Index
For InnoDB,
Use top: Primary key index, unique index, normal index, full-text index (high version start support), combined index
Principle: B + tree, adaptive Hash Index, clustered index (primary key default is secondary index, if there is no primary key, automatically select an appropriate column to build, store index and row data), secondary index (storage column data and corresponding aggregation index location)
Use 1: Combined index left matching principle
Use 2:
MySQL EXPLAIN command
The identifier for the Id:select query. Each SELECT is automatically assigned a unique identifier.
The type of the Select_type:select query.
Table: Which tables are queried
Partitions: Matching partitions
Type:join type
Possible_keys: The index that may be selected in this query
Key: The exact index used in this query.
Ref: Which field or constant is used together with key
Rows: Shows how many rows this query has scanned altogether. This is an estimate.
Filtered: Represents the percentage of data filtered by this query condition
Extra: Additional Information

4. Index failure common situation
Use function, left match, like,or (must all or conditions must be independent indexes), is NULL, etc.

5. Business
The four properties of acid are the atomicity of transactions (atomicity), consistency (consistency), isolation (isolation), persistence (durability).
Transaction ISOLATION Level:
Dirty read: Refers to a transaction that reads uncommitted data from another transaction.
Non-REPEATABLE READ: Reads a row of data from a table within a transaction, with multiple read results
Phantom reading: Both Phantom and non-repeatable reads read another transaction that has already been committed (this is different from dirty reading), and the difference is that non-repeatable read queries are the same data item, while Phantom reads are for a batch of data (such as the number of data).
Database Isolation Level:
①serializable (serialization): Can avoid dirty reading, non-repeatable reading, the occurrence of phantom reading.
②repeatable Read (Repeatable Read): Can avoid dirty read, non-repeatable read occurrence.
③read committed (Read Committed): Can avoid the occurrence of dirty reading.
④read UNCOMMITTED (READ UNCOMMITTED): lowest level, no case is guaranteed.

6. How to optimize a SQL
The first step: Understanding the SQL business and whether it can be logically optimized
Part II: Explain SQL execution plan, visual inspection there's no index to go
Part III: Check for errors that have a common effect on efficiency, such as NULL, using functions on columns, or not taking a combined index, reducing the number of join columns before join
Fourth: Increase the appropriate index
Fifth step: Not yet, try to limit the requirements (such as only the specified range of data can be counted) or other implementation (such as Timed Task Timing analysis Batch)
The sixth step: the data volume is very large, can only consider the Sub-table sub-library and other means.

Four: Data structure and algorithm (here is the part, the same idea)
1. Sorting (handwritten partial sorting algorithm)
Bubble sort, insert sort, quick row.
Bubbling: Two loops
Insert: From the second start, replace
Quick line:

2.java implementation stacks and queues
Stack: Linked list implementation, insert head Insert, delete head Delete
Queue: Linked list implementation, insert head Insert, out of queue tail removal

3.java traversing binary Tree
First: A pre-order traversal (similar to a mid-back traversal):
private void Qianout (twotreedemo<integer> headnode) {
if (headnode!=null) {
System.out.print (headnode.value+ ",");
if (headnode.leftnode!=null) {
Qianout (Headnode.leftnode);
}if (headnode.rightnode!=null) {
Qianout (Headnode.rightnode);
}
}
}

4. Linked list common correlation algorithm (hint)
First: O (1) time Delete the specified node: Replace the node's value and next with the next node, and delete the next node
Second: Find the list of the bottom of the list of K nodes, linked list median, two linked list repeat place: fast and fast pointer method (see bottom note)
Private nodedemo<integer> getk (nodedemo<integer> headnode,int k) {
if (Headnode==null | | k<0) {
return null;
}
Nodedemo Onenode = Headnode;
Nodedemo Twenode = Headnode;
int i = 1;
while (Onenode.nextnode! = null) {
Onenode = Onenode.nextnode;
if (i>=k) {
Twenode = Twenode.nextnode;
}
i++;
}
if (i<k) {
return null;
}
return twenode;
}
Third: Reverse the list of links:
private void Backnode (nodedemo<integer> headnode) {

if(headNode.nextNode == null){//如果是最后一个    this.headNode = headNode; //返回新的头部    return ;}else {    NodeDemo beforeNode = headNode;    backNode(headNode.nextNode);    headNode.nextNode.nextNode = beforeNode; // 反转    headNode.nextNode = null; // 头结点置为空}

}
Fourth one: Judging the chain list has no ring
1): Fast and Slow hands
2): Iterate and put in hash to determine whether to repeat

V: Middleware-nosql Memory Database (REDIS)-which research is often used which
1.reids Basic data types
String (Key-value), Hash (Key-value), List, Set,zset,hyperloglog (not used)

2.redis persistence mechanism
RDB persistence refers to the recording of all key-value pairs of a Redis database using a snapshot of the dataset.
AoF persistence means that all command-line records are saved as aof files in the format of the Redis command request protocol.

3. How to ensure the consistency of REDIS and DB
(Weak consistency)
Scenario 1: When reading, take it from Redis first, and if not, remove it from the database and put it in Redis. Modify Delete to invalidate data in Redis, optimize point: double Delete (delete before and after writing)
Scenario 2: Read the MySQL log binglog

4.redis Distributed Lock implementation
Method One: The official plug-in provided
Mode two: Own handwriting, note: Use Setnx,expire or set four parameters; Generate key based on the resource to be locked, the current transaction generates value, the timeout is set when the lock is received, the lock is not set about the cycle time, and the original lock is not set to determine the expiration time ; Use the watch mechanism or the Luna script when releasing the lock

5.redis transactions
A transaction (transaction) in Redis is a set of commands.
Reids transactions are not rolled back, only all and none are executed, and partial statement execution failures do not stop
MULTI (transaction start) EXEC (end) Watch (observe) unwatch (dismiss)

6.reids Expiration Policy
Timed Delete: When setting the expiration time of key, create a timer for the key, let the timer at key expiration time to temporarily, delete the key (basic not used)
Lazy Delete: Key expires when not deleted, each time the key from the database to check whether expired, if expired, delete, return null. (Built-in policies)
Delete periodically: Delete at intervals (frequency of redis.conf profile settings hz,1s refresh) expired key operation

7.redis Key-value fundamentals, such as set key value flow

VI: Middleware-Reverse proxy (NGINX)-which research is often used which

1.session processing
Scenario One: Session hold. If you use Ip_hash to direct an IP to a server
Scenario Two: Middleware session sharing. Shared as Tomcat session
Scenario Three: Independent node storage session. If the session is integrated into Redis via spring or tomcat

2. Distribution Policy
Polling (default): Each request is assigned to a different back-end server in chronological order, and can be automatically rejected if the backend server is down.
Weight (weight): Specifies the polling probability, which is proportional to the weight and access ratio, for situations where the performance of the backend server is uneven. For example:
Ip_hash (IP): Each request is allocated according to the hash result of the IP access, so that each visitor fixed access to a backend server, can solve the session problem. For example:
Fair (third-party): Allocates requests with short response times based on the response time of the backend server.

VII: Middleware-Message Queuing (ACTIVEMQ)-which research is often used which
1.ACTIVEMQ Persistence
Previous versions of amq:activemq5.3, messages stored in a file
KAHADB as the default persistence mode after the kahadb:5.4 version
JDBC: You can store messages in a database, such as: Mysql, SQL Server, Oracle, DB2.
LevelDB: Introduced from the ActiveMQ5.8, it is very similar to kahadb and is also a file-based local database storage form.

How to handle 2.ACTIVEMQ message loss
Scenario One: Message is missing when sent to broker
Workaround: Persist to the database first, delete after sending successfully, or mark Delete. Timed Task handling

Scenario Two: Broker crashes
Resolution: Message Persistence

Scenario Three: Broker-to-consumer issues
Resolution: Logical collation enables it to be re-sent (for example, when a persistent message is sent and the status is sent, the consumption succeeds is set to consumed), and the consumption is to achieve the power of

3. Repeated consumption of messages
Possible causes: Duplicate message at send, duplicate message at post
The interface of consumers to realize idempotent
Method One: Global Unique ID: Generates a global ID based on the operation and content of the business, and determines whether the operation has been performed, based on whether the global unique ID exists or not before performing the operation.
Method Two: Go to the table, set up a go-to-redo table, go to the table to set a unique index, if the go-to-table insertion succeeds then execute
Mode three: Multi-version control

4. How the Order of consumption guarantees
Scenario One: Ensure that messages that need to be sorted are sent in sequence to the same consumer queue, and that the queue has only one corresponding consumer
Scenario two: Through the business restrictions, to ensure that the previous message was consumed before the message can be sent

Eight: Framework class (Spring SPRINGMVC MyBatis)
1.SPRINGMVC flowchart
The Dispatcherservlet front controller receives the incoming request and gives it to the Handlermapping processor mapper.
Handlermapping Processor Mapper to find the appropriate Handleradapter processor adapter based on the request path (the processor adapter is the Interceptor or controller)
Handleradapter Processor adapter, handles some feature requests, returns a Modelandview object (including model data, logical view name)
Viewresolver View parser, first resolve the specific view based on the view set in the Modelandview
And then render the data in the model models to the view

2.spring IOC

3.spring AOP

How the 4.spring implements the transaction
Four different ways:
Mode one: Programmatic transaction management: code needs to be written manually, rarely used in real-world development
Mode two: Declarative transactions
Based on the Transactionproxyfactorybean approach, you need to configure each class for transaction management
Based on the ASPECTJ XML, the TX tag does not need to be changed and is configured in the XML file.
Annotation-based approach, @Transactional, simple configuration, need to add annotations in the Business layer class (use more)

5.spring Transaction propagation Behavior
transactiondefinition.propagation_required: If a transaction is currently present, the transaction is joined, and if no transaction is currently present, a new transaction is created.
Transactiondefinition.propagation_requires_new: Creates a new transaction and suspends the current transaction if a transaction is currently present.
Transactiondefinition.propagation_supports: If a transaction is currently present, the transaction is joined, and if there is no transaction, the operation continues in a non-transactional manner.
Transactiondefinition.propagation_not_supported: Runs in a non-transactional manner, suspending the current transaction if a transaction is currently present.
Transactiondefinition.propagation_never: Runs in a non-transactional manner and throws an exception if a transaction is currently present.
Transactiondefinition.propagation_mandatory: If a transaction is currently present, the transaction is joined and an exception is thrown if there is no current transaction.
Transactiondefinition.propagation_nested: If a transaction is currently present, create a transaction to run as a nested transaction for the current transaction, or if there is no current transaction, The value is equivalent to transactiondefinition.propagation_required.

Scope of 6.Spring
The default is the singleton mode, which is scope= "singleton".
1.singleton Singleton mode: Global and only one instance
2.prototype prototype mode: There will be a new instance each time the bean is fetched
3.request:request indicates that a new bean will be generated for each HTTP request, and that the bean is only in the current
The 4.session:session scope indicates that a new bean will be generated for each HTTP request, and that the bean is valid only within the valid HTTP request within the current HTTP session
The 5.global Session:global session scope is similar to the standard HTTP session scope, but it only makes sense in portlet-based Web applications. The Portlet specification defines the concept of a global session, which is shared by all the various portlets that make up a portlet Web application.

IX: Java Virtual machines and JMM
What regions are 1.JVM (hotspots), and the role of each region
Method Area: A thread-shared memory area used to store class information, constants, static variables that are loaded by the virtual machine
Run a constant pool: part of the method area that holds the various literal and symbolic references generated during the compilation period
Program counter: It is a small amount of memory space, its role is to record the yourselves thread execution of the byte code signal indicator.
Local method Stack: The local method stack acts similarly to the virtual machine stack, which executes the Java method service for the virtual machine, which is the native method used by the virtual machine.
Virtual machine stack: Each thread has its own virtual machine stack, which is created at the same time as the thread and whose life cycle is the same as the thread. The virtual machine stack describes the memory model that is executed by the Java method: When each method is executed, a stack frame (stackframe) is created to store the local variable table, the operand stack, the dynamic link, the method exit, and so on.
Heap:: Storing object instances
Direct Memory: NIO use

2.java class Loading process
The Java Virtual machine loads the data of the description class from the class file into memory, verifies and initializes the data, and finally forms the Java type that can be used directly by the virtual machine, which is the loading mechanism of the virtual machine.
Class starts from being loaded into the virtual machine's memory, and its entire lifecycle includes: Load (Loading), validate (verification), prepare (preparation), Parse (Resolution), Initialization (initialization), use (using), and unload (unloading) seven phases. Where validation, preparation, and parsing of three parts are collectively referred to as connections (linking)

3.classloader

4.java garbage collection mechanism

Ten: Socket programming (see if need to know) http://www.jfox.info/java-nio-jieshao.html
1.socket
Essentially, to achieve communication between two processes

The difference between 2.TCP and UDP
TCP: Transmission Control Protocol, connection-oriented, reliable. Ensure the data transfer is successful. (Three handshake and four breakup)
UDP: not reliable. Fast transmission speed. Less system resources.

3.bio,nio and AIO
BIO: is a blocking mode when initiating an I/O read or write operation until the application reads the stream or writes the stream to the data.
NIO: Based on event-driven thinking, Reactor (reactor) mode is often used. When an IO request is initiated, the application is non-blocking. When the socket has a stream to read or write, the application is notified by the operating system, and the application reads the stream into the buffer or writes to the system.
AIO: Also based on event-driven thinking, it is usually implemented using Proactor (pre-camera mode). In the I/O operation, call the API's read or write directly, both of which are asynchronous. For read operations, the operating system reads the data into a buffer and notifies the application that, for a write operation, the operating system writes the stream passed by the write method and proactively notifies the application. It saves the cost of traversing the event notification queue in NIO.

4.java NiO
Core: Channels,buffers,selectors
Channel: All IO starts with a channel in NiO, and the channel is a bit like a stream. Data can be read from the channel to buffer, or it can be written from buffer to the channel. (FileChannel, Socketchannel, Serversocketchannel)
Buffers: essentially a piece of memory for reading and writing, packaged as a buffer object, you can pass Allocatedirect () or allocate () Request memory space (the memory overhead generated by the allocate allocation method is in the JVM, and the cost of allocatedirect allocation is outside the JVM, which is the system-level memory allocation, Using Allocatedirect to pay particular attention to memory overflow issues, buffer needs to understand three concepts in particular, capacity, position, limit,capacity are fixed size, position is the current read and write location, Limit is a threshold-like value that controls the maximum location for reading and writing. The usual methods of buffer are clear, compact, flip, and so on, as well as static method wrap, such as buffer, which needs to be understood according to the values of capacity, position, and limit. , (Bytebuffer,intbuffer,longbuffer, etc.)
Selector: Used to detect the channel, we know which channel which event occurred, so if need to use Selector, we need to register first, It then iterates through the Selectionkey to handle the event. It has a total of Selectionkey.op_connect, selectionkey.op_accept, Selectionkey.op_read, selectionkey.op_write four types of events.

5.socket Programming Basic Process
Bio
Server-side:
Creating ServerSocket objects, binding listening ports
Listening for client requests via the Accept () method
After the connection is established, read the request information sent by the client through the input stream
Sending accent information to the client via output flow
Close related Resources
Client:
Create a socket object that indicates the address and port number of the server you want to connect to
After the connection is established, the request information is sent through the output stream to the server
Get information about the server response via the input stream
Close Response Resource

Nio:

11: Other
1. Design mode (know part can)
Design patterns broadly categorized: Create-mode, structural-pattern, behavioral-pattern
Create pattern: Hides the creation logic while creating the object instead of directly instantiating the object directly using the new operator.
Example: Factory mode, Singleton mode (at least one way), builder mode, prototype mode
Structured mode: Focus on the combination of classes and objects
Such as:
Adapter mode
SRC class, adapter->DST class
Object Adapter Mode
The adapter has an instance of the SRC class that implements the DST class interface

Bridging mode
Similar interfaces and implementation classes

Filter mode
A filtering dimension writes a filter class, and then writes a class, writes one or class
Extended dimensions can be

Adorner mode
The adornment object accepts requests from all clients and forwards those requests to the real object. In this way, you can add new functionality before and after the real object is called.

Proxy mode,
The proxy class and the proxy class implement the same interface
An instance of a proxy class in a proxy class

Behavioral patterns: Focus on communication between objects
Such as: Responsibility chain mode, iterator mode, command mode
Responsibility chain Model
Similar interceptors, etc.

Command mode:
Separates callers from Callee's behavior

Interpreter mode:
Each syntax is an interpreter class

Iterator mode:
Change the collection class's view traversal and add and delete rows to separate

Note:
1) Transient: Prevents a property from being serialized
2) CAS algorithm: There are 3 operands, memory value V, old expected value A, new value to modify B. If and only if the expected value A and the memory value of the V phase, the memory value of V is modified to B, otherwise do nothing. There may be ABA problems and how to avoid ABA (with version number)
3) Fast and Slow pointer method: Set two pointers confirm acceptance of this offer

Frequently asked questions and partial answers in Java interview (2018)

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.