Remember the 2017.3.21 Ali interview experience, Java direction

Source: Internet
Author: User
Tags instance method redis
1. What are the new features of JavaJava language compiler class library tools Java Runtime 1.1 Java languageLambda expressions (closures) allow you to use a function as a parameter to a method, or to think of code as data.
Arrays.aslist ("A", "B", "D"). ForEach (E->system.out.println (e));
Arrays.aslist ("A", "B", "D"). ForEach (e-> {
    System.out.print (e));
    System.out.print (e);
} );
Arrays.aslist ("A", "B", "D"). Sort ((E1, E2)-> E1.compareto (E2));
Adding functional interfaces can be implicitly converted to lambda expression @functioninterface, and the default method and static method do not affect the contract of functional interfaces. The default method of the interface and the static method, all the implementations will inherit it by default (if necessary, you can override this default implementation) method reference: Constructor reference class::new (no parameters), static method reference Class::static_method, Arbitrary object class :: Method, a specific object Instance::method duplicate annotations 1.2 new features of the Java compilerParameter name, easy to get parameter name 1.3 new features of Java class LibraryOptional a container, you can save the value of type T, or simply save NULL, and provide useful methods so that we do not have to display a null check. If the instance of the optional class is Non-null, Ispresent () returns True, or false, in order to prevent optional from being null, the Orelseget () method generates a default value through a callback function. The map () function Converts the value of the current optional, and then returns a new optional instance. The Stream's true functional style has been introduced into Java, greatly simplifying the processing of the set framework. Date/time API Clock class, specify time zone, get current time, date, Time Parrellelsort () method, greatly improve array sorting speed on multi-core machines.
optional< String > fullName = optional.ofnullable (null);
System.out.println ("Full Name is set?" + fullname.ispresent ()); 
System.out.println ("Full Name:" + fullname.orelseget (()-> "[None]")); 
System.out.println (Fullname.map (S-> "Hey" + S + "!"). OrElse ("Hey stranger!"));
2. How to achieve synchronizedThe object header Mark lock is stored in the object header, which is divided into two pieces of information, the first part is used to store data for the object's own run-time, such as the HASHCODE,GC age, and the other part is used to store pointers to the method area type data. The bias lock bias lock is actually an optimal lock, which is designed to reduce the performance loss of data in the absence of competition. The core idea is that the lock will favor the first thread to get it, and that the thread holding the biased lock will never need to be synchronized in the next execution, when the lock has no other thread to fetch. Lightweight locks reduce the performance losses that traditional heavyweight locks produce using operating system mutexes without multiple threading competition. Spin lock sychronized Lock is a kind of heavyweight lock, in mutually exclusive state, the thread that does not get lock is blocked, while the operation of suspending thread and resuming thread needs to be done in kernel state. The so-called spin lock, which is to allow the process of not getting the lock to run itself for a period of time from the loop (default to open), but the cost of not suspending the thread is that the thread will always occupy the processor, and if the lock takes a very short time, the spin-wait works well, whereas the spin lock consumes a lot of processor resources, so The spin time must have a certain limit, over the limit has not been acquired lock, it is necessary to suspend the thread. In order to reduce the performance consumption of lock and release locks, these states will escalate with the competition, in turn, stateless locks, bias locks, lightweight locks, spin locks and heavyweight locks. Locks can only be upgraded and cannot be degraded. Synchronized usage: Cosmetic method and code block: A thread gets an object lock, but another thread can access a method or code that is not synchronized, the method of synchronization and the method without synchronization are not mutually affected, one thread enters the synchronization method, gets the object lock, Other threads still have access to methods that are not synchronized, and the two locked object methods are mutually exclusive. Simultaneously modifies the static method and the instance method, but may alternately carry on the mutual non-interference. Synchronized flaw: When a thread enters the synchronization method to acquire an object lock, other threads must wait or block when accessing the object's synchronization method, which is fatal to the high concurrency system. If a thread has a dead loop inside the synchronization method, the object lock will never be released and the other threads will wait forever. The synchronized block has the advantage that the contents of the synchronization operation can be independent of the synchronization object. The metaphor of the image

For example, an object is like a big house, and the door opens forever. There are a lot of rooms in the house (ie method).

These rooms have a locked (synchronized method) and are not locked (common method). A key was placed at the door of the room, and the key opened all the locked rooms.

In addition, I compare all the threads that want to call the object method to the person who chengxiang into a room in the house. So much for everything, so let's look at how these things work.

Here we begin by clarifying our prerequisites. The object has at least one synchronized method, otherwise the key has no meaning. Of course, we will not have this subject.

A man wanted to enter a locked room, and he came to the door of the house and saw the key there (indicating that no one else had to use the locked room for the time being). So he went up to get the keys and used the rooms according to his plan. Note that he will return the key once every time he uses a locked room. Even if he had to use two locked rooms in a row, he would return the keys in the middle.

Therefore, the general principle of the use of the key is: "With the use of borrowed, the use of that is also." ”

At this time other people can unrestricted use of those unlocked rooms, one can use one, two people can use a room, there is no limit. But if someone wants to go into a locked room, he's going to go to the gate and look at it. Have the key of course take to go, no words, can only wait.

If a lot of people are waiting for this key, when the key returns, who will give priority to the key. Not guaranteed. As in the previous example, the guy who wants to use two locked rooms in a row, if there are other people waiting for the key when the key is still in the middle, there is no guarantee that this guy will get it again.

Take a look at the sync code block again. and synchronized methods are a little different.

1. In terms of size, the synchronized code block is smaller than the synchronization method. You can think of the sync code block as a space separated by a locked screen in a unlocked room.

2. The synchronized code block can also be artificially specified to obtain key for some other object. It's like specifying which key to use to unlock this screen, you can use the key of the room, you can also specify the key to another house to open, so you have to run to another house to bring the key, and the house with the key to open the house with the lock of the screen.

Remember that the key to the other house that you obtained does not affect others entering the room without locks.

Why should I use a synchronized block of code? I think it should be like this: the first part of the synchronization of the program is very affecting the efficiency of the operation, and a method is usually to create some local variables, and then do some operations on these variables, such as operations, display and so on, and the more code covered by synchronization, the greater the impact on efficiency. So we usually try to narrow the scope of the impact.
3. Introduction to the transactionhttp://blog.csdn.net/zhanghaor/article/details/57084350

Four properties of a transaction: persistence, atomicity, isolation, consistency. Where consistency is the most basic attribute, the other three properties are guaranteed to be consistent. Consistency refers to the fact that the data is in a meaningful state, which is semantically rather than grammatical. such as consistency in the transfer process. In the database implementation scenario, consistency can be divided into database external consistency and database internal consistency. The former is guaranteed by an externally applied code, that is, an application must invoke the operation of account A and account B within the same transaction in the operation of the database in which the transfer is performed, 㐊 the database itself can be solved. The latter has a database to ensure that a set of operations within the same transaction must be executed successfully, which is the atomicity of transaction processing. In order to achieve atomicity, all updates to the database need to be written to the log through the log, and if a part of a transaction succeeds, but the subsequent operation cannot continue, the successful operation is undone through the backtracking log, thus achieving the purpose of all operations failure. The typical scenario is that the database system crashes and restarts, at which point the database is in an inconsistent state, and a crash recovery process must be performed to read the log for redo (replay all operations that have been performed but not successfully written to disk, ensuring durability), Undo all transactions that have not yet been successfully committed at the time of the crash (undo all of the actions that have been performed, but not committed, to ensure atomicity). After the crash recovery is finished, the database is restored to a consistent state. In the case of multiple transactions running in parallel, instant assurance of the atomicity of each transaction can still result in inconsistent results of data. This introduces isolation, which guarantees that the data that each transaction can see is always consistent, as if other concurrent transactions do not exist. To achieve isolation there are two typical locks: one is the pessimistic lock, which means that the current transaction locks all objects involved in the operation of W, and releases them to other objects when it is finished. In order to improve performance as much as possible. Invented a variety of particle size, a variety of properties of the lock, in order to solve the deadlock problem, but also invented a two-stage lock protocol and other columns of technology. Optimistic lock (optimistic locking) relative pessimistic lock, optimistic lock hypothesis that the data will not cause conflicts in general, so when the data is submitted to update, it will formally detect the conflict or not, if found conflict, so that the return of the user error information, Let the user decide how to do it. In contrast to pessimistic locks, optimistic locks do not use the lock mechanism provided by the database when processing the database. The general way to implement optimistic locks is to record data versions. The data version, which is an additional version identifier for the data. When reading the data, the value of the version ID is read together, the data is updated every time, and the version identity is updated. When we submit an update, we judge that the current version of the corresponding record in the database table is compared to the version ID that was first taken out.If the current version number of the database table is equal to the version identity value that was first taken out, it is updated, otherwise it is considered an expired data. There are two ways to implement a data version, the first is to use a version number, and the second is to use a timestamp.4. Synchronization of Redis and relational databasesRedis is a high-performance key-value database. The emergence of Redis, to a large extent, compensates for the shortage of such key-value storage in memcached, and in some cases can complement the relational database well. It provides a python,ruby,erlang,php client and is easy to use.
According to our general use of the Redis scenario should be this:

In other words: We will first go to the Redis to determine whether the data exists, and if so, return the cached data directly. If it does not exist, it will go to the database, read the data, and cache the data into the Redis. Application: If the amount of data is relatively large, but not often update the situation (such as user ranking) and the second type of Redis, and the first case is different, the specific situation please see:


Here we will first go to Redis to determine whether the data exists, if there is, then directly update the corresponding data (bar corresponding to the updated key records, such as also saved to Redis, key for Save_update_keys), and the updated data returned to the page, and if not saved , you will update the contents of the database first, and then save the data to Redis. Behind the work, the background will have the relevant mechanism to the REDIS in the Save_update_keys stored key, read out, find the corresponding data, updated to the DB. Advantages: The main purpose is to use Redis as a database, update access to data than DB block, very suitable for large data volume of frequent changes (such as micro-BO), shortcomings, the dependence on Redis is very large, to do a good job of data storage downtime. 5. Database index Database index, is a database management system in a sort of data structure to facilitate rapid query, update database table data, the implementation of the index is usually a B-tree (all nodes balance factor is 0 of the fork Lookup tree) and its variant B + tree.

In addition to data, the database system maintains a data structure that satisfies a particular lookup algorithm, which refers to data in some way, so that advanced lookup algorithms can be implemented on these data structures. This data structure is the index. One is to increase the storage space of the database, and the second is to spend more time inserting and modifying the data (because the index will also change).


The figure above shows a possible way of indexing. On the left is the datasheet, a total of two columns and seven records, and the leftmost is the physical address of the data record (note that logically adjacent records are not necessarily physically contiguous on disk). To speed up the Col2 lookup, you can maintain a two-fork lookup tree shown on the right, each node containing the index key value and a pointer to the corresponding data record physical address, so that the binary lookup can be used to obtain the corresponding data within the complexity of O (log2n).

Creating an index can greatly improve the performance of your system.

First, you can guarantee the uniqueness of each row of data in a database table by creating a unique index.

Second, you can greatly speed up the retrieval of data, which is the main reason to create indexes.

Third, you can speed up the connection between tables and tables, especially in terms of realizing the referential integrity of the data.

Finally, when you use grouping and sorting clauses for data retrieval, you can also significantly reduce the time to group and sort in a query.

In the process of querying, the optimization of the hidden device can be used to improve the performance of the system by using the index.


One might ask: why is there so many advantages to adding an index, and why not to create an index for each column in the table? Because there are many disadvantages to adding indexes.

First, it takes time to create indexes and maintain indexes, which increase as the amount of data increases.

Second, the index needs to occupy the physical space, in addition to the data table occupies the data space, each index also occupies a certain physical space, if you want to establish a clustered index, then need more space.

Third, when the data in the table is added, deleted and modified, the index will be maintained dynamically, thus reducing the data maintenance speed.


Generally, indexes should be indexed on these columns:

You can speed up your search on columns that you often need to search for.

On a column that is a primary key, enforces the uniqueness of the column and the arrangement structure in the Organization table

Often used on connected columns, these columns are mostly foreign keys and can speed up the connection

Create an index on a column that needs to be searched based on scope because the index is already sorted and its specified range is contiguous

Create an index on a column that is often sorted, because the index is already sorted so that the query can take advantage of the sort of the index, speeding up the sorting query time

Creating indexes on columns that are frequently used in the WHERE clause speeds up the judgment of the condition.



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.