ThreadLocal (thread variable copy)
Synchronized implements memory sharing, Threadlocal maintains a local variable for each thread.
With space-time, it is used for data isolation between threads, providing a copy of each thread that uses the variable, each of which can independently change its own copy without conflicting with the other thread's copy.
The Threadlocal class maintains a map that stores a copy of the variable for each thread, the key of the element in the map is the thread object, and the value is a copy of the variable for the corresponding thread.
Threadlocal plays a huge role in spring, and it appears in the management of the request scope of the beans, transaction management, task scheduling, AOP and other modules.
Most of the beans in spring can be declared as singleton scopes, encapsulated with threadlocal, so stateful beans can work in multi-threading in singleton manner.
Links: In-depth study of java.lang.ThreadLocal class
The
Java memory model:
Java Virtual machine specification divides Java runtime data into six types.
1. Program counter: is a data structure that holds the memory address of a program that is currently executing normally. The multithreading of a Java Virtual machine is realized by rotating threads and allocating processor time, in order to recover to the correct location after thread switching, each thread needs a separate program counter, which is "thread private".
2.Java virtual machine stack: Thread-private, same as thread life cycle, used to store local variable table, Operation Stack, method return value. A local variable table has a base data type, and a reference to the object.
3. Local method Stack: Much like the virtual machine stack, but it is the native method service used for the virtual machine.
4.Java Heap: An area of memory that is shared by all threads, with almost all of the object instances allocating memory here.
5. Method Area: The area shared by each thread, storing the class information loaded by the virtual machine, constants, static variables, compiled code.
6. Run a constant pool: represents the Constants table in each class file at run time. Includes several constants: numeric constants at compile time, methods, or references to fields.
Links: java in the JVM virtual machine detailed
"Can you talk about when and what the Java GC was, and what did it do?" ”
At what time:
1. The new generation has an Eden area and two survivor zones, first placing objects in the Eden area, and placing them on one of the survivor areas if there is not enough space, and if they still do not fit, it will trigger a minor GC that occurs in the Cenozoic. Put the surviving object in another survivor area, then empty the memory of Eden and the previous survivor area. In a GC, if you find objects that still don't fit, put those objects into memory in the old age.
2. Large objects and long-lived objects go directly into the old age zone.
3. Each time the minor GC is executed, the object to be promoted to the older age should be analyzed, and if the older objects in the old age area are now larger than the remaining size of the old age area, perform a full GC to maximize the space in the old area.
What to do: No search from the GC roots, and there are no resurrected objects after a token cleanup.
What to do: The New generation: replication cleanup; old age: Tag-purge and tag-compression algorithms; permanent: the class loader itself that holds classes in Java and loads classes.
What are GC roots: 1. The referenced object in the virtual machine stack is 2. The object referenced by the static property in the method area, the constant reference to object 3. The object referenced by JNI (that is, generally speaking, the native method) in the local method stack.
Links: Java gc stuff (UP)
Links: Things to do with Java GC (bottom)
Links: Introduction to CMS garbage collector
Both Synchronized and lock are reentrant locks, and the same thread enters the synchronization code again. You can use the lock that you have acquired.
Synchronized is a pessimistic locking mechanism, an exclusive lock. The Locks.reentrantlock, however, is to complete an operation without locking each time, assuming that there is no conflict, and retry until it succeeds because of a conflict failure. Reentrantlock Applicable Scenarios
- A thread needs to be interrupted while waiting for control of a lock
- Need to deal with some wait-notify,reentrantlock inside the condition application, can control which thread notify, lock can bind multiple conditions.
- With the fair lock function, each incoming thread will be queued.
Links: Synchronized keywords, Lock, and explain the difference between them
StringBuffer is thread-safe, each time the string is manipulated, String generates a new object, and StringBuffer does not; StringBuilder is not thread-safe
Links: The difference between String, StringBuffer and StringBuilder
Fail-fast: Mechanism is an error mechanism in the Java Collection (Collection). Fail-fast events can occur when multiple threads operate on the contents of the same collection.
For example, when a thread a passes through a iterator to traverse a collection, if the contents of that collection are changed by another thread, thread a accesses the collection and throws an Concurrentmodificationexception exception, generating the Fail-fast event
Happens-before: If there is a happens-before relationship between the two operations, the result of the previous operation will be visible to the subsequent operation.
1. Program Order rules: Each action in a thread is happens-before to any subsequent action in that thread.
2. Monitor lock rule: Unlocks a monitor lock, happens-before to the locking of the subsequent lock on the monitor.
3.volatile variable rule: Writes to a volatile field, happens-before to any subsequent reading of this volatile field.
4. Transitivity: If a happens-before B, and B happens-before C, then a Happens-before c.
5. Thread Start rule: the Start () method of the thread object Happens-before every action on this thread.
Volatile and synchronized four different points:
1 granularity is different, the former is for variables, the latter locks objects and classes
2 syn Blocking, volatile threads not blocking
3 SYN guarantees three major characteristics, volatile does not guarantee atomicity
4 syn compiler optimizations, volatile does not optimize volatile have two characteristics:
1. Ensure that this variable is visible to all threads, that a thread modifies the value of the variable, and that the new value is visible to other threads, but not multithreading-safe.
2. Prohibit command reordering optimization.
How volatile guarantees memory visibility:
1. When writing a volatile variable, JMM flushes the shared variable in the local memory corresponding to the thread to main memory.
2. When reading a volatile variable, JMM will set the local memory corresponding to that thread to be invalid. The thread next reads the shared variable from the main memory.
Synchronization: It is the completion of a task that relies on another task, and a dependent task can only be completed after the task that is dependent is completed.
Async: There is no need to wait for a dependent task to complete, just to notify the dependent task to complete what work, as long as their task is completed, even if the task is completed, the dependent tasks will be notified back. (The feature of async is notification). Call and send text messages to describe synchronous and asynchronous operations.
Blocking: The CPU stops waiting for a slow operation to complete before the other work is completed.
Non-blocking: non-blocking is when this slow execution, the CPU to do other work, wait for this slow completion, the CPU will continue to complete the subsequent operation.
Non-blocking can cause thread switching to increase, and increasing CPU usage time can compensate for the switching cost of the system.
Links: The volatile keyword parsing of java concurrency programming
CAS (Compare and Swap) lock-free algorithm: CAS is optimistic locking technology, when multiple threads try to update the same variable using CAs, only one of the threads can update the value of the variable, while the other threads fail, the failed thread is not suspended, but is told that the competition failed, And you can try again. CAS has 3 operands, a memory value of V, an old expected value of a, and a new value to be modified 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.
Links: Non-blocking synchronization algorithm and CAS (Compare and Swap) lock-free algorithm
The role of the thread pool: When the program starts, it creates several threads that respond to processing, called the thread pool, which is called the worker thread.
First: Reduce resource consumption. Reduce the consumption caused by thread creation and destruction by reusing the threads that have been created.
Second: Improve response speed. When a task arrives, the task can be executed immediately without waiting for the thread to be created.
Third: Improve the manageability of threads.
Common thread pool: Executorservice is the main implementation class, which is commonly used with Executors.newsinglethreadpool (), Newfixedthreadpool (), Newcachedtheadpool (), Newscheduledthreadpool ().
Links: Thread pool principle
Links: Thread Pool principle analysis
class loader working mechanism:
1. Load: Import the Java binaries into the JVM and generate the class file.
2. Connect: a) Check: Verify the correctness of loading class file data B) Prepare: Allocate storage space for static variables of Class C) parsing: Turn a symbolic reference into a direct reference
3: Initialize: Initializes the static variables of the class, static methods, and static blocks of code.
Parental delegation Model: The class loader receives a class load request, first delegating the request to the parent class loader to complete the user-defined loader--application loader, extension ClassLoader, and the launch class loader.
Links: In-depth understanding of Java Virtual Machine notes-Parental delegation model
Links: Things that the JVM class loads
Links: JVM (1): Java class loading mechanism
Consistent hash:
Memcahed Cache:
Data structure: Key,value on
Method of Use: Get,put and other methods
Links: hashcode (), equal () method in-depth analysis
REDIS data structure: string-string (key-value type)
The hash structure of the hash-Dictionary (hashmap) Redis allows you to modify only one item property value just as you would update a property in a database
list-list Implementation Message Queuing
set-Collection Utilization Uniqueness
Sorted set-ordered collection can be sorted to achieve data persistence
Links: Spring + Redis for data caching
Java Auto-Boxing unpacking in-depth analysis
Talk about the Java reflection mechanism
How do I write an immutable class?
Index: b+,b-, full-text index
The MySQL index is a data structure designed to make the database efficiently find data.
The commonly used data structure is b+tree, each leaf node not only holds the relevant information of the index key, but also increases the pointer to the neighboring leaf node, thus forming a b+tree with sequential access pointers, and the purpose of this optimization is to improve the performance of different interval accesses.
When to use the index:
- Fields that often appear after the group By,order by and Distinc keywords
- Tables that are frequently connected to other tables and should be indexed on the join field
- Fields that often appear in the WHERE clause
- Fields that are used as query selections often appear
- Java Learning Exchange QQ Group: 589809992 We'll learn java! together.
Links: Mysql:innodb Storage engine B + Tree index algorithm
Links: MySQL index behind the data structure and algorithm principles
Spring IOC (Control inversion, dependency injection)
Spring supports three types of dependency injection, namely, attribute (setter method) injection, construction injection, and interface injection.
In spring, the entities that make up the application and the objects managed by the spring IOC container are called beans.
The spring IOC container instantiates the bean through a reflection mechanism and establishes a dependency between the beans.
Simply put, beans are objects that are initialized, assembled, and managed by the spring IOC container.
The process of getting the Bean object, first loading the configuration file with resource and starting the IOC container, and then getting the bean object through the Getbean method, you can call his method.
Scope of Spring Bean:
There is only one shared bean instance in the Singleton:spring IOC container, which is generally the Singleton scope.
Prototype: Each request produces a new instance of the bean.
Request: Each HTTP request produces a new instance of the bean.
Links: Spring Framework IOC container and AOP parsing
Links: A brief talk on the usage analysis of spring frame annotations
Links: 69 Interview questions about spring-the ultimate list
The common advantage of the agent: the business class only needs to pay attention to the business logic itself, and ensure the reusability of the business class.
Java Static proxy:
The proxy object and the target object implement the same interface, and the target object acts as a property of the proxy object, and the proxy object can add other business processing logic before and after invoking the corresponding method of the target object.
Disadvantage: A proxy class can only proxy one business class. If the business class increases the method, the corresponding proxy class also increases the method.
Java Dynamic Agent:
Java Dynamic agent is to write a class to implement the Invocationhandler interface, overriding the Invoke method, the Invoke method can be enhanced processing of the logic of the writing, the public proxy class at run time to clarify their own proxy object, At the same time can implement the method of the proxy class, and then the implementation of the class method can be enhanced processing.
In fact: Method of proxy object = Enhanced processing + method of proxied Object
The differences between JDK and cglib generate dynamic proxy classes:
The JDK dynamic agent can only generate proxies for classes that implement an interface (instantiating a class). At this point the proxy object and the target object implement the same interface, the target object as a property of the proxy object, the specific interface implementation, you can call the target object corresponding method before and after adding other business processing logic
Cglib is the implementation of a proxy for a class, mainly by generating a subclass of the specified class (without instantiating a class), overriding the methods in it.
Spring AOP Application Scenario
Performance detection, access control, log management, transactions, and more.
The default policy is to use the JDK dynamic Agent technology if the target class implements the interface, and if the target object does not implement the interface, the default is to use the Cglib proxy
SPRINGMVC Operating principle
- Client request submitted to Dispatcherservlet
- The handlermapping is queried by the Dispatcherservlet controller and is found and distributed to the specified controller.
- After the controller invokes the business logic processing, it returns Modelandview
- Dispatcherservlet query One or more Viewresoler view resolvers to find the Modelandview specified view
- The view is responsible for displaying the results to the client
Links: Spring: Annotations-based spring MVC (top)
Links: Spring: annotation-based spring MVC (bottom)
Links: Springmvc and Struts2 difference and comparison summary
Links: Comparison of Springmvc and Struts2
An HTTP request
DNS domain name resolution –> initiates a TCP three handshake –> initiates an HTTP request after establishing a TCP connection –> the server responds to an HTTP request, the browser gets HTML code –> the browser parses the HTML code, and request the resources in the HTML code (such as JavaScript, CSS, pictures, etc.) to render the page to the user –> the browser
Design a storage system that stores massive amounts of data: Design a logical layer called "middle tier", in this layer, the database of massive data capture, make cache, run in the memory of the server, similarly, when there is new data to come, also first to cache, and then try to persist into the database, this is a simple idea. The main step is load balancing, distributing requests from different users to different processing nodes, and then caching them to update the data to the primary database at timed intervals. The process of reading and writing uses a mechanism similar to optimistic locking, which can be read all the time (while writing the data), but there will be a version tag each time it is read, and if the read version is lower than the cached version, the data will be re-read, which is not a lot to endure.
Links: The difference between HTTP and HTTPS
Links: Why is HTTPS more secure, first look at these
Links: HTTP request messages and HTTP response messages
Links: HTTP Request mode: Get and post comparison
Session and Cookie:cookie can allow the server to track each client's access, but each client access must be returned to these cookies, if a lot of cookies, the invisible increase in the client and server data transfer volume,
The session is a good solution to this problem, the same client each time and server interaction, the data store through the session to the service side, do not need to return all the cookie value each time, but return an ID, each client first access to the servers generated by the unique ID, The client simply returns this ID, which is usually a cookie named Jsessionid. This allows the server to use this ID to retrieve the KV value stored on the server.
Session and Cookie timeout issues, cookie security issues
Distributed Session Framework
- Configure the server, the Zookeeper Cluster Management Server can manage all the server's configuration files uniformly
- Sharing these sessions is stored in a distributed cache, can be written and read at any time, and performance is good, such as Memcache,tair.
- Encapsulates a class that inherits from HttpSession, stores the session in this class, and then deposits it in the distributed cache
- Since cookies cannot be accessed across domains, synchronization of the session is SessionID to different domain names.
Adapter mode: An interface is adapted to another interface, and Java I/O inputstreamreader the reader class to InputStream, enabling a byte stream to be quasi-swapped.
Decorator Mode: Keep the original interface, enhance the original function.
FileInputStream implements all the interfaces of the InputStream, Bufferedinputstreams inherits from FileInputStream is the concrete adorner implementation, saves the inputstream reads the content in the memory, and improve read performance.
Spring Transaction Configuration method:
1. Pointcut information for locating business class methods that implement a facet of a thing
2. Transaction properties that control transaction behavior, including the object isolation level, transaction propagation behavior, time-out, and rollback rules.
Spring uses Aop/tx Schema namespaces and @transaction annotation techniques to make declarative things configuration.
Mybatis
Each MyBatis application is centered on an instance of a Sqlsessionfactory object. First, the configuration file is read through resource with a byte stream, and then the sqlsessionfactory is created through the Sqlsessionfactorybuilder (). Build method. The Sqlsessionfactory.opensession () method is then used to create a sqlsession for each database transaction service.
Went through the MyBatis initialization –> create sqlsession–> Run SQL statement, return the results of the three procedures
The difference between servlet and filter:
The whole process is: Filter pre-processing the user request, then send the request to the servlet for processing and generate a response, and finally filter then post-process the server response.
Filter has several uses:
Filter can make a request for a specific URL and do preprocessing and post-processing accordingly.
Intercept the client's httpservletrequest before HttpServletRequest arrives at the servlet.
You can also modify the HttpServletRequest header and data as needed to check the httpservletrequest.
Intercept HttpServletResponse before HttpServletResponse arrives at the client.
You can also modify the HttpServletResponse header and data as needed to check the httpservletresponse.
In fact, the filter is very similar to the servlet, except that filter cannot generate a response directly to the user. In fact, the code in the filter Dofilter () method is the generic code drawn from the service () method of multiple Servlets, which allows for better reuse by using the filter.
The life cycle of the filter and servlet:
1.Filter initialization at Web server startup
2. If a servlet is configured with 1, the servlet is also initialized when Tomcat (Servlet container) starts.
3. If the servlet does not have configuration 1, the servlet is not initialized at Tomcat startup, but is initialized when the request arrives.
4. Each request is initialized and the request is destroyed after responding to the request.
After the 5.Servlet is initialized, it will not be logged off with the end of the request.
6. When Tomcat is turned off, the Servlet and filter are logged off in turn.
The difference between HashMap and Hashtable.
1, HashMap is non-thread-safe, Hashtable is thread-safe.
2, HashMap the key and value are allowed to have a null value exists, and Hashtable is not.
3, because of the problem of thread safety, hashmap efficiency is higher than Hashtable.
The implementation mechanism of HASHMAP:
- Maintaining an array of each element is a linked list, and each node in the list is a data structure for a entry[] key-value pair.
- The implementation of the array + linked list features, Find Fast, insert delete is also fast.
- For each key, his corresponding array index subscript is int i = hash (key.hashcode) & (len-1);
- Each newly added node is placed at the top of the list, and then the newly added node points to the original list header
- Java Learning Exchange QQ Group: 589809992 We'll learn java! together.
HashMap and TreeMap differences
Links: The difference between HashMap and TreeMap in Java in-depth understanding
HashMap conflict
Links: HashMap Conflict resolution method and principle analysis
Links: How HashMap works
Links: The difference between HashMap and Hashtable
Links: 2 ways to make HashMap thread safe
The difference between Hashmap,concurrenthashmap and Linkedhashmap
- Concurrenthashmap is the use of lock segmentation technology to ensure thread-safe, lock segmentation technology: First the data into a section of storage, and then to each piece of data with a lock, when a thread occupies a lock to access one of the data, other segments of the data can also be accessed by other threads
- Concurrenthashmap is safe in the middle of each segment (segment)
- Linkedhashmap maintains a doubly linked list, which can be read in the order in which the data is written
CONCURRENTHASHMAP Application Scenarios
The 1:concurrenthashmap scenario is high concurrency, but does not guarantee thread safety, while the synchronized HashMap and HashMap lock the entire container, and Concurrenthashmap does not need to lock the entire container after locking. Only need to lock the corresponding segment is good, so can guarantee high concurrent access, improve efficiency.
2: Can be multithreaded write.
Concurrenthashmap the HashMap into a number of segmenet.
1.get, do not lock, first locate to segment and then find the head node to read operations. While value is a volatile variable, it is guaranteed that the most recent value is guaranteed to be read in the race condition, and if the read value is NULL, it may be being modified, then the Readvalueunderlock function is called, and the lock guarantees that the data read is correct.
2.Put will be locked, all added to the head of the hash chain.
3.Remove will also be locked, because next is the final type is immutable, so the node before the deletion must be copied again.
4.CONCURRENTHASHMAP allows multiple modifications to be performed concurrently, and the key is to use the lock separation technique. It uses multiple locks to control changes to different segment of the hash table.
The concurrenthashmap scenario is high concurrency, but does not guarantee thread safety, while the synchronized HashMap and Hashtable lock the entire container, and Concurrenthashmap does not need to lock the entire container after locking. Only need to lock the corresponding segment is good, so can guarantee high concurrent access, improve efficiency.
Concurrenthashmap can guarantee that every call is atomic, but there is no guarantee that multiple invocations are atomic operations.
Links: Java Collection-concurrenthashmap principle analysis
The difference between vector and ArrayList
Links: The difference between vector and ArrayList in Java
Executorservice service = executors .... Executorservice service = new Threadpoolexecutor () executorservice service = new Scheduledthreadpoolexecutor ();
Threadpoolexecutor Source Code Analysis
The status of the thread pool itself:
Wait for the task queue and working set:
Main state lock of the thread pool:
Survival time and size of the thread pool:
Internal workings of the 1.2 threadpoolexecutor
With the above-defined data, let's look at how the internals are implemented. Doug Lea's whole idea is summed up in 5 words:
- If the current pool size poolsize is less than corepoolsize, a new thread is created to perform the task.
- Enter the wait queue if the current pool size poolsize is greater than corepoolsize and the wait queue is not full
- If the current pool size poolsize is greater than corepoolsize and less than maximumpoolsize, and the waiting queue is full, a new thread is created to perform the task.
- If the current pool size poolsize is greater than corepoolsize and is greater than maximumpoolsize, and the wait queue is full, the deny policy is called to process the task.
- Thread constructor Each thread will not exit immediately after executing the task, but will check the waiting queue to see if the threads task needs to be executed, and if there is no new task in the KeepAliveTime, then it will exit.
Executor Package Structure
Copyonwritearraylist: Add lock when writing, when adding an element, the original container is copied, copy a new container, and then write in the new container, and then write the original container reference to the new container, and read the old container to read the data, So it is possible to read concurrently, but this is a weak consistency strategy.
Usage Scenario: Copyonwritearraylist is suitable for scenarios where read operations are much larger than write operations, such as caching.
Linux Common commands: Cd,cp,mv,rm,ps (process), Tar,cat (view content), Chmod,vim,find,ls
The necessary conditions for deadlock
- Mutex has at least one resource in a non-shared state
- Occupy and wait
- Non-preemption
- Loop wait
To solve the deadlock, the first is a deadlock prevention, that is, the above four conditions are not set up at the same time. Second, the rational allocation of resources.
The third is to use the banker algorithm, if the process requests the amount of resources operating system remaining can be satisfied, then allocate.
Inter-process Communication mode
- Pipe: A pipe is a half-duplex mode of communication in which data can only flow in one direction and can only be used between processes that have affinity. A process's affinity usually refers to a parent-child process relationship.
- Famous pipe (named pipe): A well-known pipe is also a half-duplex mode of communication, but it allows communication between unrelated processes.
- Semaphore (Semophore): Semaphore is a counter that can be used to control access to shared resources by multiple processes. It is often used as a locking mechanism to prevent a process from accessing the shared resource while other processes are accessing the resource. Therefore, it is primarily used as a means of synchronization between processes and between different threads within the same process.
- Message Queuing: Message Queuing is a linked list of messages, stored in the kernel and identified by message queue identifiers. Message Queuing overcomes the disadvantages of less signal transmission information, only unformatted byte stream, and limited buffer size.
- Signal (sinal): A signal is a more complex form of communication that notifies the receiving process that an event has occurred.
- Shared memory: Shared memory is the mapping of memory that can be accessed by other processes, which is created by a process, but can be accessed by multiple processes. Shared memory is the fastest IPC approach and is specifically designed for low-efficiency operation of other interprocess communication modes. It is often used with other communication mechanisms, such as semaphores, to achieve synchronization and communication between processes.
- Socket (SOCKET): Socket is also an inter-process communication mechanism, unlike other communication mechanisms, it can be used for process communication between different machines.
- Java Learning Exchange QQ Group: 589809992 We'll learn java! together.
Process-to-thread differences and linkages
Process scheduling algorithm for operating system
A detailed description of the hierarchical storage structure of computer systems
A database transaction is a series of operations performed as a single logical unit of work.
Links: Four characteristics of database transactions and the isolation level of transactions
MySQL Database optimization Summary
MYSQL Optimization Common methods
MySQL storage engine--myisam differs from InnoDB
About the paradigm in SQL database
Hibernate's first-level cache is provided by the session, so it only exists in the session's lifetime, when the program calls save (), update (), Saveorupdate (), and calls the query interface List,filter, Iterate, if there are no corresponding objects in the session cache, hibernate will add the object to the first level cache and the cache will disappear when the session is closed.
Hibernate's first-level cache is built into the session, cannot be uninstalled, and can not be configured for any configuration level cache is implemented by the Key-value map method, when the entity object is cached, the object's primary key ID is the map key, and the entity object is the corresponding value.
Hibernate level Two cache: puts all the obtained data objects into the second level cache based on the ID. Hibernate level Two cache policy is a cache policy for ID queries that updates the cache while deleting, updating, and adding data.
The difference between a process and a thread:
Process: Each process has its own code and data space (process context), and there is a significant overhead of switching between processes, and a process contains 1–n threads.
Threads: The same class of threads share code and data space, each thread has a separate run stack and program counter (PC), and thread switching overhead is small.
Threads and processes are divided into five phases: Create, ready, run, block, terminate.
Multi-process means that the operating system can run multiple tasks (programs) at the same time.
Multithreading refers to the execution of multiple sequential streams in the same program.
In Java to implement multi-threading, there are three ways, one is to continue the thread class, the other is to implement the Runable interface, there is to implement the callable interface.
Can switch use string to make arguments?
A. Prior to Java 7, switch can only support Byte,short,char,int or its corresponding wrapper class and Enum type. In Java 7, String support was added.
What are the common methods of object?
A. Method equals tests whether two objects are equal
B. Method clone for object copy
C. Method GetClass returns the class object associated with the current object
D. Method notify,notifyall,wait are used for thread synchronization of a given object
Java four kinds of references, soft and weak, and the use of the scene
A. Solving an oom problem with soft and weak references: A hashmap is used to save the path of the picture and the mapping between the soft references associated with the corresponding picture object, and the JVM automatically reclaims the space occupied by these cached picture objects when the memory is low, effectively avoiding the problem of oom.
B. Implement caching of Java objects by means of the soft-and-Object-regain method: For example, we create a class for employee, if we need to query an employee's information every time. It takes a lot of time to rebuild an instance if it's just been queried in a few seconds. We can use the combination of soft reference and HASHMAP, first save the reference aspect: a soft reference to the instance of an Employee object reference and save the reference to HashMap, key for this employee's Id,value for this object's soft reference, on the other hand is to take out the reference, Whether there is a soft reference to the employee instance in the cache, if any, obtained from a soft reference. If there is no soft reference, or if the instance obtained from the soft reference is NULL, rebuild an instance and save a soft reference to the new instance.
C. Strong references: If an object has a strong reference, it will not be reclaimed by the garbage collector. Even if there is not enough memory space, the JVM does not reclaim it, but instead throws a outofmemoryerror error that causes the program to terminate unexpectedly. If you want to break the association between a strong reference and an object, you can explicitly assign a reference to NULL, so that the JVM reclaims the object at the appropriate time.
D. Soft reference: When using soft references, if the memory space is sufficient, soft references can continue to be used without being reclaimed by the garbage collector, and soft references are reclaimed by the garbage collector only when there is insufficient memory.
E. Weak reference: An object with a weak reference has a more ephemeral life cycle. Because when the JVM is garbage collected, weak references are recycled whenever a weak reference object is found, regardless of whether the current memory space is sufficient. However, because the garbage collector is a low-priority thread, it is not always possible to quickly discover weak reference objects.
F. Virtual reference: As the name implies, is the form of a dummy, if an object only holds a virtual reference, then it is equivalent to no reference, at any time may be reclaimed by the garbage collector.
What is the difference between the role of hashcode and equal?
A. The same is used to identify whether 2 objects are equal, the Java collection has a list and set two classes, where set does not allow the element to be repeated implementation, the method is not allowed to repeat the implementation, if you use equal to compare, if there are 1000 elements, you new one element out, It is necessary to call 1000 times equal to compare them with each other to see if they are the same object, which will greatly reduce the efficiency. Hashcode is actually the storage address of the returned object, if there is no element in this position, the element is stored directly above, if the element already exists in this position, then call the equal method to compare with the new element, the same word will not be saved, hash to the other address.
The meaning and difference of override and overload
A.overload as the name implies is a reload, it can show the polymorphism of the class, can be the function can have the same function name but the parameter name, return value, type cannot be the same, or can change the parameter, type, return value but the function name remains unchanged.
B. Is the meaning of Ride (rewrite), when the subclass inherits the parent class, you can define a method that has the same name and parameters as its parent class, and when the subclass calls the function, the subclass's method is called automatically, and the parent class is equivalent to overwritten (overridden).
Specifically, you can go to C + + to overload, override (overwrite) The Difference instance analysis view
The difference between an abstract class and an interface
A. A class can inherit only a single class, but it is possible to implement multiple interfaces
B. There can be a constructor in an abstract class, and there cannot be a construction method in an interface
C. All methods in an abstract class are not necessarily abstract, and you can choose to implement some basic methods in an abstract class. And the interface requires that all methods must be abstract.
D. Abstract classes can contain static methods, which are not available in the interface
E. There can be ordinary member variables in an abstract class, which is not available in the interface.
The principles and features of several ways to parse xml: DOM, SAX, pull
A.dom: Consume memory: First read the XML document into memory, then use the DOM API to access the tree structure and get the data. This is easy to write, but it consumes memory. If the data is too big, mobile phone is not good enough, the phone may crash directly
B.sax: High resolution, memory-intensive, event-driven: more simply, sequential scanning of documents notifies the event handler when the document starts and ends, elements (element) Start and end, document ends, and so on. The event handler acts accordingly, and then continues the same scan until the end of the document.
C.pull: Similar to SAX and event-driven, we can call its next () method to get the next parse event (that is, start document, end document, start tag, end tag), When you are in an element, you can call Xmlpullparser's Getattributte () method to get the value of the property, or you can call its nexttext () to get the value of this node.
The difference between wait () and sleep ()
Sleep comes from the thread class, and wait comes from the object class
During the call to the sleep () method, the thread does not release the object lock. Calling the wait method thread frees the object lock
Sleep does not sell system resources, wait to let system resources other threads can consume CPU
Sleep (milliseconds) needs to specify a sleeping time when the time is automatically awakened
The difference between heap and Stack in Java, the memory mechanism of Java
A. A reference to a base data type that is more than a variable and an object is allocated on the stack
B. Heap memory used to hold objects and arrays created by new
C. class variables (static modified variables), the program allocates memory for class variables in the heap at the time of loading, and memory addresses in the heap are stored on the stack
D. Instance variables: When you use the Java keyword New, the system in the heap is not necessarily contiguous space allocated to the variable, is based on the fragmented heap memory address, the hash algorithm is converted to a long series of numbers to characterize the variable in the heap "physical location", instance variable life cycle – When a reference to an instance variable is lost, it is included in the recyclable "list" by the GC (garbage collector), but the memory in the heap is not released immediately
E. Local variables: By declaring in a method, or a piece of code (such as a For loop), execution to it in the stack to open up memory, when the local variable one but out of scope, memory immediately released
The implementation principle of Java polymorphism
A. In abstract terms, polymorphism means that the same message can be used in a variety of different ways depending on the sending object. (Sending a message is a function call)
B. The principle of implementation is dynamic binding, the method of the program call is dynamically bound in the runtime, tracing the source code can be found that the JVM through the automatic transformation of parameters to find the right way.
Summary of the questions of Java backend development in major companies