Java Basics-1

Source: Internet
Author: User
Tags ack connection pooling mutex

Is there a memory leak in Java?

A memory leak is an object or variable that is no longer being used by the program and occupies storage space in memory.

If the developer forgets to release the allocated memory, it will cause a memory leak.

In Java, there are two criteria for determining whether a memory space conforms to the garbage collection mechanism:

    1. Null is given to the object and is not used in the future
    2. New value assigned to object, memory space reassigned

There are two main cases of memory leaks:

    1. The space requested in the heap is not released
    2. object is no longer in use, but remains in memory

The garbage collection mechanism in Java resolves Scenario 1, so memory leaks are mostly case 2

In Java, the main causes of memory leaks are:

    1. Static collection Classes
    2. Various connections, such as database connections, network connections, and IO connectivity
    3. Listener
    4. The scope of the variable is unreasonable
    5. Singleton mode may cause memory leaks
What is the difference between heaps and stacks in Java

Heaps and stacks are places where data is stored in memory

The heap is primarily used to store objects, and stacks are used to execute programs

Stacks are accessed faster than heaps

The heap can allocate memory dynamically in the run

When the main () method exits, the variables in the stack are recycled

What is the Java collections framework

The Java collections Framework contains a number of collection interfaces, the implementation classes of these interfaces, and the algorithms that manipulate them.

Set

Represents a set concept in mathematical sense. feature is that elements in a collection cannot be duplicated

HashSet

TreeSet: The elements in the container are ordered

List

Also known as the Orderly collection.

Objects are saved in the order in which they are entered, with the ability to precisely control where each element of the list is inserted and deleted.

At the same time, it can save duplicate objects.

Map

Provides a data structure that maps from a key to a value. It is used to hold key-value pairs where values can be duplicated and the keys are unique.

HashMap is based on the hash list implementation, the object Hashcode can be used for quick query.

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.

Cookie and Session Differences
    1. The cookie is stored on the client, the data is stored in the client's browser, and the session mechanism takes the server-side scenario and the data is stored on the server.
    2. Cookie security is not enough, session information is stored on the server, so it is more secure.
    3. Higher cookie Performance
    4. A single cookie cannot hold more than 4 KB of data, and the session does not have this problem.
Hibernate benefits
    1. Improve development efficiency
    2. You can fully adopt object-oriented thinking and don't need to care about the relational model of database
    3. It's a good transplant.
    4. Supports transparent persistence
Using Hibernate to improve performance
    1. Lazy Loading
    2. Caching technology
    3. Refine query statements
Paging mechanism

When the amount of data is large, if you take the data out at once, it not only wastes time, but also consumes a lot of memory.

The paging mechanism reduces the amount of data in the result set of the query and reduces the memory consumption, so it can significantly reduce the response time and help improve the usability of the system and enhance the user experience.

Method:

    1. Framework comes with paging mechanism
    2. SQL Statement Implementation Paging
Gc

Automatically detects the scope of the object and frees up storage space that is no longer being used.

Role

    • Allocating memory
    • Ensure that the referenced object is not reclaimed by mistake
    • Reclaim memory space for objects that are no longer referenced
Garbage collection algorithm
    1. Reference counting: The drawback is that you cannot handle circular reference problems
    2. Tag-clear: Marks all objects that start from the root node, with the disadvantage of not having contiguous memory space, less productivity of contiguous memory space than contiguous memory space
    3. Replication algorithm: Divides the memory space into two blocks, each time the in-memory surviving object is copied into the unused memory block, and then the memory block being used is purged. For the new generation (fewer surviving objects, more garbage objects)
    4. Tag-Compression algorithm: When you clear an Unlabeled object, all the surviving objects are also compressed to one end of the memory, and then all the space on the boundary is cleared. Applicable to the old age.
    5. Sub-generational
Dead lock

When a thread needs to hold multiple locks, it is possible to generate a deadlock.

Thread A currently holds the mutex lock1, and thread B currently holds the mutex Lock2.

A want to lock2,b also want to lock1, each other to try to get each other, and refused to release their own, fell into the endless waiting/blocking.

This situation becomes a deadlock.

ArrayList, Vector, LinkedList difference
Container Dynamic Expansion Size sync? safe? Efficiency
ArrayList Scalable arrays 1.5 times times Non-synchronous Not thread safe Index or delete elements at the end of the high efficiency
Vector Scalable arrays Twice times Most methods are synchronized Thread Safety Index or delete elements at the end of high efficiency, multi-threading
LinkedList Scalable arrays Non-thread safe Bidirectional list implementation, inserting high data, inserting or deleting elements in a specified position high efficiency
Comparison of sorting algorithms
Sorting Algorithms best time Average Time Worst Time Secondary Storage Stability Notes
Simple selection sorting $O (n^2) $ $O (n^2) $ $O (n^2) $ $O (1) $ Not stable N Hours better
Direct Insert Sort $O (N) $ $O (n^2) $ $O (n^2) $ $O (1) $ Stability Most of them are better ordered.
Bubble sort $O (N) $ $O (n^2) $ $O (n^2) $ $O (1) $ Stability N Hours better
Hill sort $O (N) $ $O (NLOGN) $ $O (N^s) (1<S<2) $ $O (1) $ Not stable S is the selected grouping
Quick Sort $O (NLOGN) $ $O (NLOGN) $ $O (n^2) $ $O (LOGN) $ Not stable Better when N is big
Heap Sort $O (NLOGN) $ $O (NLOGN) $ $O (NLOGN) $ $O (1) $ Not stable Better when N is big
Merge sort $O (NLOGN) $ $O (NLOGN) $ $O (NLOGN) $ $O (N) $ Stability Better when N is big
What is value passing and reference passing
    • Value passing: When a method call is made, the actual delegate passes its value to the formal parameter, and the parameter initializes a temporary storage unit with the value of the argument, so the value is the same as the storage unit, and the change of the parameter does not affect the argument.
    • Reference passing: When a method is called, the object is passed, the shape participates in the argument to the same storage unit, and the change to the parameter changes the argument.
Three basic elements of an object-oriented
    1. Encapsulation: Encapsulation is the process and data is surrounded, access to data only through the defined interface. Object-oriented computing begins with this basic concept that the real world can be portrayed as a series of fully autonomous, encapsulated objects that access other objects through a protected interface.
    2. Inheritance: Inheritance is a hierarchical model of a junction class and allows and encourages the reuse of classes, which provides a way to articulate commonalities. A new class of objects can be derived from existing classes, a process known as class inheritance. The new class inherits the attributes of the original class, which is called the derived class (subclass) of the original class, and the original class is called the base class of the new class (The parent Class). Derived classes can inherit methods and instance variables from their base classes, and classes can modify or add new methods to make them more suitable for special needs.
    3. Polymorphism: Polymorphism means that objects of different classes are allowed to respond to the same message. Polymorphism consists of parameterized polymorphism and inclusion polymorphism. Polymorphism language has the advantage of flexibility, abstraction, behavior sharing and code sharing, which solves the problem of application function with the same name.
Can I proactively notify the JVM to do garbage collection?

Because of the garbage collector's presence, the Java language does not provide a way for developers to release allocated memory, and developers cannot call the garbage collector in real time to garbage collection of an object or all objects.

However, development can call the System.GC () method to "notify" the garbage collector to run, and of course, the JVM will not run immediately.

Differences between heap and Stack in Java
    1. Stack memory is primarily used to store basic data types and reference variables, and heap memory is used to hold objects created at runtime
    2. The heap is primarily used to store objects, and stacks are used primarily to execute programs
What are the thread states, and how are they converted?
    1. New (new): Just created, not yet called the Start method
    2. Runnable (Operational): State that can be run in a Java virtual machine
    3. Blocked (blocked): When a thread acquires an internal object lock on another thread, it must not
    4. Waiting (wait): When a thread waits for another thread to notify the scheduler of a condition, it enters its own wait state
    5. Timed Waiting (timed Wait): A method that has a timeout parameter causes the thread to wait for a time, and if a timeout or notification occurs, it switches to the operational state
    6. Terminated (terminated): died because the Run method exited gracefully or the Run method was terminated because an exception was not caught

The difference between a thread and a process, what are the pros and cons

Thread: Refers to an execution unit in which the program executes the program code during execution. 4 states: Run, ready, hang, end.

Process: Refers to a program that is being executed.

Create a line turndown less resources are required to create a process.

When you enter a URL in the browser, such as http://www.taobao.com, what happens after you press ENTER?

From a technical point of view, such as the browser, the network (UDP, TCP, HTTP, etc.), as well as the server, and so on a variety of participating objects on the resulting series of activities, please refer to all the key technology points as far as possible.

1.DNS域名解析:浏览器缓存、系统缓存、路由器、ISP的DNS服务器、根域名服务器。把域名转化成IP地址。 2.与IP地址对应的服务器建立TCP连接,经历三次握手:SYN,ACK、SYN,ACK 3.以get,post方式发送HTTP请求,get方式发送主机,用户代理,connection属性,cookie等 4.获得服务器的响应,显示页面-----------------------------------------------------------1 查缓存2 DNS解析3 获取ip4 建立tcp连接5 发http数据6 接受http数据并解析7 close-------------------------------------------------------------------1、根据域名查询域名的IP。浏览器缓存->操作系统缓存->本地域名服务器缓存->域名服务器。2、得到IP后发起基于TCP的HTTP请求。如果浏览器存储了该域名下的cookie,那么会把cookie放入HTTP请求头里。3、TCP被包装为IP包,通过网络(可能经过很多路由器、交换机)发送到IP地址对应的服务器。这个服务器可能只是一个反向代理服务器,如果是,则HTTP请求被转交给内网中真实的某一个服务器(可能有多个服务器)。4、服务器分析HTTP请求,生成HTTP响应(可能是HTML、图片等)后,将响应发送给客户端浏览器。5、浏览器得到响应后,根据响应内容显示结果。如果响应的是图片,则将图片”画“在浏览器页面上;如果是HTML,则渲染HTML并”画“在浏览器页面上,在分析HTML时,若发现引用了其他资源,例如css、图片等,则发起HTTP请求,得到响应资源。
The difference between cat, more, and less commands in Linux

Can be used to view the contents of a file

Command difference function Comparison
Cat Display the contents of the entire file at once, and also connect multiple files to display, often in conjunction with redirection symbols, for situations where file content is small So so
More Generally used to display the contents of the file more than one screen, providing the ability to turn pages. Provides a paginated display. Strong
Less Generally used to display the contents of the file more than one screen, providing the ability to turn pages. Page, jump, find. More powerful
    • What are the effects and costs of indexing? How do I build an index? How the Index Works
    • Hash algorithm
    • Algorithm: Binary search algorithm, bubble sort, select sort algorithm, insert sort, merge, Hill, fast algorithm
    • Lock: Optimistic lock and pessimistic lock
    • Under what circumstances will a deadlock occur? How do I avoid deadlocks?
    • JVM GC: Introduces garbage collection mechanism, garbage collection algorithm.
    • The reflection mechanism of Java
    • What are the Java collection classes, and which scenarios are used in each
    • How to quickly find a file under Linux
    • How to set environment variables under Linux
How to view TCP connection status under Linux
LISTEN:          侦听来自远方的TCP端口的连接请求  listen SYN-SENT:    再发送连接请求后等待匹配的连接请求     syn-sentSYN-RECEIVED:再收到和发送一个连接请求后等待对方对连接请求的确认  syn-receivedESTABLISHED: 代表一个打开的连接FIN-WAIT-1:  等待远程TCP连接中断请求,或先前的连接中断请求的确认FIN-WAIT-2:  从远程TCP等待连接中断请求CLOSE-WAIT:  等待从本地用户发来的连接中断请求CLOSING:     等待远程TCP对连接中断的确认LAST-ACK:    等待原来的发向远程TCP的连接中断请求的确认TIME-WAIT:   等待足够的时间以确保远程TCP接收到连接中断请求的确认CLOSED:      没有任何连接状态
    • Outline the basic flow of an HTTP request
    • What is JDBC and why is JDBC required? What is the implementation principle?
    • The difference between get and post
    • What is the difference between a cookie and a session, respectively?
    • Why do I need to encode? How UTF-8 and GBK are encoded
    • Introduce the next Jdk,jre and JVM respectively
    1. What is the data structure of HashMap? How it is implemented. The difference between the Hashtable,concurrenthashmap and the

    2. What's the use of indexes? How do I build an index?
    3. How is ArrayList implemented, the difference between ArrayList and LinkedList? ArrayList how to achieve capacity expansion.
    4. The Equals method implements
    5. Object oriented
    6. Thread state, what's the difference between blocked and waiting
    7. How the JVM loads bytecode files
    8. JVM GC,GC algorithm.
    9. What happens when the full GC is present, and what happens to the Yong GC.

JVM Memory model

Java memory model, which is the model of Java program memory at run time, while Java code is running on a Java virtual machine, it also refers to the runtime memory model of the Java Virtual machine.

    1. Java Runtime Data area
    2. How transactions are implemented
Technical depth
    1. Have you seen the JDK source code, see the class implementation principle is what.
    2. HTTP protocol
    3. TCP protocol
    4. Consistent hash algorithm
    5. How the JVM loads bytecode files
    6. How the ClassLoader unloads bytecode
    7. The difference between IO and NIO, NIO benefits
    8. Java thread Pool Implementation principle, KeepAliveTime parameters such as the role.
    9. HTTP connection Pooling Implementation principle
    10. Database connection pooling Implementation principles
    11. How the database is implemented
Technical framework
    1. See what open source framework of source code
    2. What are the pros and cons of using Redis,redis? How does redis achieve capacity expansion?
    3. Netty is how to use the thread pool, why use it so
    4. What are the pros and cons of using spring,spring?
    5. Spring's IOC container initialization process
    6. Spring's IOC container implementation principle, why beans can be found through byname and Bytype
    7. Spring AOP Implementation Principles
    8. How the message middleware is implemented, and what are the technical difficulties
System architecture
    1. How to build a highly available system
    2. Which design patterns can increase the scalability of the system
    3. Introduces design patterns such as template mode, command mode, policy mode, adapter mode, bridging mode, decoration mode, observer mode, state mode, visitor mode.
    4. Abstract ability, how to improve the efficiency of research and development.
    5. What is high cohesion low coupling, please give examples of how to achieve
    6. What situation with the interface, what condition with the message
    7. If AB two systems depend on each other, how to release dependencies
    8. How to write a design document, what is a directory
    9. What scenarios should be split system, what scenario should merge system
    10. What is the difference between the system and the module, and what scenarios are used
Distributed Systems
    1. Distributed transactions, two-phase commit.
    2. How to implement a distributed lock
    3. How to implement distributed session
    4. How to guarantee the consistency of messages
    5. Load Balancing
    6. Forward proxy (client proxy) and reverse proxy (server-side proxy)
    7. CDN Implementation Principle
    8. How to improve the system's QPS and throughput
Actual combat capability
    1. Have you dealt with the problem on the line? There is a memory leak, a CPU utilization level, and how the application is handled without responding.
    2. Have you encountered any technical problems in the development? How to solve the
    3. If there is a billions of whitelist, high concurrent queries are required daily during the day and need to be updated at night to design this feature.
    4. How Sina Weibo is enabling Twitter to Subscribers
    5. How Google returns the search results to the user within a second.
    6. 12306 how the booking system of the website is implemented, how to ensure that no ticket is not oversold.
    7. How to implement a second kill system, to ensure that only a few users can buy a product.
Soft power
    1. How to learn a new technology, such as how to learn Java, focus on learning what
    2. What new technologies are in focus
    3. How to deal with a lot of work tasks and very miscellaneous
    4. How Project Latency is handled
    5. It's not the same as my colleagues ' design ideas.
    6. How to ensure the quality of development
    7. What is career planning? Short term, what is the long term goal
    8. What is the planning of the team?
    9. To introduce myself from work to the present and grow there
Basic concepts
  1. Multiple threads can manipulate one data at a time, and to ensure the accuracy of the data, you can change the part of the operation to synchronize.
  2. Concurrency: In the operating system, there are several programs in a period of time that are running from the start to running, and these programs are running on the same processor. Two of these concurrency relationships are synchronous and mutex, respectively
  3. Mutex: The use of critical resources between processes is called mutual exclusion.
  4. Synchronization: The relationship between processes is not the relationship of mutually exclusive critical resources, but the interdependent relationship. Further note: The output of the previous process is the input of the latter process, and the second process must wait when the first process does not output. A group of concurrent processes that have synchronization relationships send each other information called messages or events.
  5. There is concurrent pseudo concurrency and true concurrency, pseudo-concurrency refers to the single-core processor concurrency, true concurrency refers to the multi-core processor concurrency.
  6. Parallel: In a single processor multi-channel program design system, the process is alternately executed, showing a concurrency of external special; In multiprocessor systems, processes can be executed alternately, and can overlap. A program on a multiprocessor can implement parallel processing. In this sense, parallelism is for multi-processor. Parallel is a concurrent occurrence of multiple simultaneous events, with the meaning of concurrency, but concurrency is not necessarily parallel, it is also said that concurrent events do not necessarily occur at the same time.
  7. Multithreading: Multithreading is the logical layer concept of programming, which is a piece of code that runs concurrently in a process. Multithreading enables switching between threads to execute.
  8. Async: Asynchronous and synchronous are relative, synchronization is sequential execution, execution of one after execution of the next, need to wait, coordinated operation. Asynchronous is independent of each other, in the process of waiting for an event to continue to do their own things, do not have to wait for the event to complete and then work. A thread is a way to implement Asynchrony. Async is the main thread that lets the calling method do not need to wait for another thread to finish synchronously, so that the main thread can Cheng Gan other things.
  9. Async and multithreading are not an equal relationship, asynchronous is the ultimate goal, multithreading is just a means for us to implement Asynchrony. Asynchronous is when a call request is sent to the callee, and the caller can do something else without waiting for the return of the result. The implementation of Asynchrony can be handled by multithreading or by handing it to another process.
  10. constructor is executed when an object is new
  11. Description of inheritance in @java: A subclass can inherit only one parent class; inheritance is transitive; the parent class is generally generic, and subclasses are more specific.
  12. When an object is no longer referenced, it becomes garbage can be recycled, but the thread can run independently even if it is not referenced.

Java Basics-1

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.