Questions on Java basic plane

Source: Internet
Author: User
Tags comparable deprecated finally block thread class volatile

Hibernate's caching mechanism
1. Hibernate is a persistent layer framework that accesses physical databases frequently to reduce the frequency of application access to physical data sources, thereby improving application performance.
The data in the cache is a copy of the data in the physical data source, the application reads and writes data from the cache at run time, and at a particular moment or event synchronizes the cache and the data from the physical data source.
2, Hibernate first-level cache is also called "Session cache", it is built-in, cannot be uninstalled (cannot be uninstalled means that this cache is not optional,
Must have the function, can not cancel the session cache).
Because the life cycle of a Session object usually corresponds to a database transaction or an application transaction, its cache is a transaction-scoped cache.
3, Hibernate level two cache, also known as "Sessionfactory Cache", due to the life cycle of the Sessionfactory object and the entire process of the application,
Therefore, hibernate level two caches are process-wide or cluster-scoped caches, and concurrency problems are possible, so you need to adopt appropriate concurrent access policies.
This policy provides a transaction isolation level for cached data.
4. Whenever we manage the hibernate cache (managing the caches), when you pass an object to the Save (), update (), or Saveorupdate () method,
Or when an object is obtained using the load (), get (), list (), iterate (), or scroll () method, the object is added to the internal cache of the session.

2. What are the differences between threads, threads, and processes, and how Java implements Threads
A thread is the smallest unit that the operating system can perform operations on, which is included in the process and is the actual operating unit of the process.

The difference: A thread is a subset of processes, a process can have many threads, and each thread performs different tasks in parallel. Different processes use different memory spaces, and all threads share the same amount of memory space. Each thread has a separate stack of memory to store local data.

Implementing threads: Inheriting the thread or implementing the Runnable interface, both of which can implement thread differences is that Java does not support multiple inheritance of classes, but allows multiple interfaces to be called, and if you want to inherit other classes you can only call the Runnable interface

3. What is the difference between the start () and run () methods in the Thread class?
The start () method is used to start the newly created thread, and start calls the run () method internally, which is not the same as calling the run () method directly. When you call the run () method,
The start () method starts a new thread only if it is called in the original thread and no new thread is started.

4. What are the volatile variables in Java?
Volatile is a special modifier that can only be used by member variables. Multithreaded operations on member variables are transparent to other threads in the absence of a synchronization class for Java concurrency programs.
A volatile variable guarantees that the next read operation will occur after the previous write operation


5. What is thread safety? is vector a thread-safe class?
If your code is in a process where multiple threads are running at the same time, these threads may run the code at the same time. If the result of each run is the same as the single-threaded run, and the value of the other variable is the same as expected, it is thread-safe. The same instance object of a thread-safe counter class will not have a computational error if it is used by multiple threads.
Vectors are thread-safe with synchronous methods, and ArrayList similar to it are not thread-safe.

6. How do I stop a thread in Java?
Java provides a rich API but does not provide an API for stopping threads.
JDK 1.0 originally had some control methods like Stop (), suspend (), and resume () but because of the potential deadlock threat they were deprecated in subsequent JDK versions,
The designer of the Java API then did not provide a compatible and thread-safe way to stop a thread.
When the run () or call () method finishes executing, the thread ends automatically, and if you want to end a thread manually, you can use the volatile Boolean variable to exit the run () method's loop or cancel the task to break thread.

7. What happens when a thread runs out of an exception?
If the exception is not caught, the thread will stop executing. Thread.uncaughtexceptionhandler is an inline interface for dealing with abrupt interruptions of threads caused by uncaught exceptions.
When an uncaught exception causes the thread to break, the JVM uses Thread.getuncaughtexceptionhandler () To query the thread's Uncaughtexceptionhandler and pass the thread and exception as arguments to the handler's Uncaughtexception () method for processing.


8. What is the difference between notify and Notifyall in Java?
Because multithreading can wait for a single-monitor lock, Java API designers provide methods to notify them when they wait for the condition to change, but these methods are not fully implemented.
The Notify () method does not wake up a specific thread, so only one thread waits for it to be useful.
Notifyall () Wakes all threads and allows them to scramble for locks to ensure that at least one thread can continue to run.


9, why wait, notify and notifyall These methods are not inside the thread class?
One obvious reason is that the locks provided by Java are object-level rather than thread-level, and each object has a lock, which is obtained through the thread.
The wait () method in the calling object is meaningful if the thread waits for some locks. If the wait () method is defined in the thread class, it is not obvious which lock the thread is waiting for.
Simply put, because Wait,notify and Notifyall are both lock-level operations, they are defined in the object class because the locks belong to the objects.

10. What is the difference between synchronous collections in Java and concurrent collections?
Both synchronous and concurrent collections provide the appropriate thread-safe collection for multithreading and concurrency, although the concurrency collection is more extensible.
Concurrent collections like Concurrenthashmap, not only provide thread safety, but also improve scalability with modern technologies such as lock separation and internal partitioning.

11. What is the difference between heap and stack in Java?
Each thread has its own stack memory, which is used to store local variables, method parameters, and stack calls, and variables stored in one thread are not visible to other threads.
The heap is a common area of memory shared by all threads. Objects are created in the heap, in order to increase the efficiency of the thread will get a cache from the heap to its own stack, if multiple threads use the variable can cause problems, then the volatile variable can play a role, it requires the thread to read the value of the variable from main memory.

12. What is a thread pool? Why use it?
Creating threads takes expensive resources and time, and if the task is to create a thread, the response time is longer and the number of threads a process can create is limited.
To avoid these problems, when the program starts, it creates several threads that respond to processing, called the thread pool, which is called a worker thread. Starting with JDK1.5, the Java API provides a executor framework that allows you to create different thread pools. For example, a single thread pool, one task at a time, a fixed number of thread pools or a pool of cache threads (an extensible thread pool for programs that are suitable for many short-lived tasks).

13, how to avoid deadlocks?
Deadlock deadlock in Java multithreading refers to two or more two processes in the execution process, because of contention for resources caused by a mutual waiting phenomenon, if there is no external force, they will not be able to proceed.
The following four conditions must be met for a deadlock to occur:
Mutex condition: A resource can only be used by one process at a time.
Request and hold condition: When a process is blocked by a request for resources, it remains in place for the resources that have been obtained.
Non-deprivation: the resources that the process has acquired cannot be forcibly stripped until the end of use.
Cyclic wait condition: a cyclic waiting resource relationship is formed between several processes.
The simplest way to avoid deadlocks is to stop the loop waiting condition, set the flags, sort all the resources in the system, and stipulate that all process request resources must operate in a certain order (ascending or descending) to avoid deadlocks.

14. What is the difference between a live lock and a deadlock in Java?
This is an extension of the above topic, and the difference between a live lock and a deadlock is that the state of a thread or process in a live lock is constantly changing, and a live lock can be considered a special kind of starvation. A realistic example of a live lock is two people in a narrow corridor, two people are trying to avoid each other to allow each other to pass, but because the direction of avoidance is the same result in the end no one can pass the corridor. Simply put, the main difference between a live lock and a deadlock is that the state of the former process can be changed but cannot continue to execute.


15, how to detect whether a thread has a lock?
In Java.lang.Thread there is a method called Holdslock (), when and only if the thread has a lock on a specific object it returns TRUE.

16, there are three threads t1,t2,t3, how to ensure that they are executed sequentially?
There are several ways to get threads to execute in a particular order in multiple threads, and you can use the join () method of the thread class to start another thread in one thread, and another thread to finish the thread. In order to ensure the order of three threads you should start the last one (T3 call t2,t2 call T1) so T1 will be completed first and T3 finalized.

17. What is the difference between the submit () and execute () methods in the Java thread pool?
Two methods can submit a task to the thread pool, the return type of the Execute () method is void, it is defined in the executor interface, and the Submit () method can return a future object holding the result of the calculation, which is defined in the Executorservice interface. It extends the executor interface, and other thread pool classes like Threadpoolexecutor and Scheduledthreadpoolexecutor have these methods.

18. What is a blocking method?
The blocking method means that the program waits for the method to complete without doing anything else, and the ServerSocket accept () method is to wait for the client to connect. The blocking here means that the current thread is suspended until the result of the call returns, until the results are returned. In addition, there are asynchronous and non-blocking methods that are returned before the task is completed.

19. What is a busy loop in multi-threading?
A busy loop is when a programmer uses a loop to wait for a thread, unlike the traditional method wait (), sleep () or yield (), which discards CPU control, and the busy loop does not abandon the CPU, it is running an empty loop. The purpose of this is to preserve the CPU cache, in which a waiting thread wakes up in a multi-core system and may run in another kernel, which rebuilds the cache. It can be used to avoid rebuilding the cache and reducing the time it takes to wait for a rebuild.

20. What happens if a thread inside a synchronization block throws an exception?
Regardless of whether your sync block is normal or abnormally exited, the thread inside will release the lock, so I prefer the sync block to the lock interface, because it does not cost me the energy to release the lock,
This function can release the lock implementation in the finally block.

21. What is the difference between calling the wait () and sleep () methods in multi-threaded Java?
Wait and sleep in Java programs cause some form of pause, which can meet different needs.
The wait () method is used for inter-thread communication, and if the wait condition is true and other threads are awakened, it releases the lock, and the sleep () method simply frees the CPU resources or causes the current thread to stop executing for a period of time.
But the lock is not released.

22, the database optimization
1, hardware optimization, improve machine performance, increase hardware and so on;
2, the Optimization query statement, will be strong in the where conditions before, with exists instead of in operation, and so on;
3, optimize the index, establish an effective index and check and repair the missing statistics, etc.
4, database System file optimization, the data files, index files, log files on different disks, improve the degree of parallelism, etc.
5, Big Data segmentation, when a table of data size reached hundreds of millions of, the index has basically played a role: to build an index to spend a lot of time, the query due to scan Large index table also takes a lot of time. To make the index work, you can split a large table into several small tables according to a field.


23. What are the similarities and differences between abstract class and interface (interface)?
A: Abstract classes and interfaces cannot be instantiated, but you can define references to abstract classes and interface types. If a class inherits an abstract class or implements an interface that requires all of its abstract methods to be implemented, the class still needs to be declared as an abstract class. Interfaces are more abstract than abstract classes, because constructors can be defined in abstract classes, can have abstract methods and concrete methods, and constructors are not defined in an interface, and the methods are all abstract methods. Members in an abstract class can be private, default, protected, public, and members of the interface are all public. Member variables can be defined in an abstract class, whereas member variables defined in an interface are actually constants. Classes with abstract methods must be declared as abstract classes, and abstract classes may not necessarily have abstract methods


24, explains the difference between final, finally, finalize.
A:
-final: modifier (keyword) has three uses: If a class is declared final, it means that it can no longer derive a new subclass, i.e. it cannot be inherited, so it and abstract are antonyms. Declaring variables as final ensures that they are not changed in use, and that the variable declared as final must be given the initial value at the time of declaration, whereas in subsequent references only the non-modifiable can be read. A method that is declared final can also be used only and cannot be overridden in a subclass.
-finally: usually put in try...catch ... The subsequent construct always executes the code block, which means that the program executes either normally or unexpectedly, the code here can be executed as long as the JVM is not closed, and the code that frees the external resource is written in the finally block.
-Methods defined in the Finalize:object class that allow the use of the Finalize () method in Java to do the necessary cleanup before the garbage collector clears the object from memory. This method is called by the garbage collector when the object is destroyed, and by overriding the Finalize () method, you can defragment the system resources or perform other cleanup work.

25. Describe the storage performance and characteristics of ArrayList, Vector and LinkedList.
A: Both ArrayList and vectors use arrays to store data, which is larger than the actual stored data in order to add and insert elements, both of which allow the element to be indexed directly by ordinal, but the insertion element involves memory operations such as array element movement, so the index data is fast and the data is inserted slowly. The method in vectors is a thread-safe container because of the addition of the synchronized modifier, but the performance is ArrayList poor, so it is already a legacy container in Java. LinkedList uses a two-way linked list for storage (associating memory cells with additional references to form a linear structure that can be indexed by ordinal, with a more efficient use of memory than an array of contiguous storage), which requires forward or back traversal by ordinal index data , but you only need to record the items before and after inserting the data, so the insertion speed is faster. Vectors are legacy containers (containers provided in earlier versions of Java, Hashtable, Dictionary, BitSet, Stacks, properties are legacy containers) and are deprecated. However, because ArrayList and linkedlisted are non-thread-safe, if you encounter multiple threads operating in the same container scenario, You can use the Synchronizedlist method in the tool class collections to convert it to a thread-safe container before using it (this is the application of the decorating mode, which creates a new object in the constructor of another class to enhance the implementation).

26, List, MAP, set three interface access elements, what are the characteristics of each?
A: The list accesses elements in a specific index and can have duplicate elements. Set cannot hold repeating elements (using the Equals () method of the object to distinguish whether the element is duplicated). Map holds the key-value pair (Key-value pair) mapping, and the mapping relationship can be one-to-many. Both the set and map containers have two implementations based on the hash store and the sorting tree, and the hash-based version theory accesses the time complexity to O (1), while the implementation based on the sort tree version, when inserting or deleting elements, forms a sort tree by the key (key) of the element or element to achieve the sorting and deduplication effect.

27. How do TreeMap and TreeSet compare elements when sorting? How does the sort () method in the Collections tool class compare elements?
A: TreeSet requires that the class to which the object belongs must implement the comparable interface, which provides the CompareTo () method of the comparison element, which is called back when the element is inserted and the method compares the size of the element. TreeMap requires that keys stored in a key pair map must implement the comparable interface to sort the elements according to the key. The sort method of the collections tool class has two overloaded forms, the first one requiring the object to be placed in the incoming sorting container to implement the comparable interface for comparing the elements, and the second not mandatory to require that the elements in the container be comparable, but that the second argument is required. The parameter is a subtype of the comparator interface (it is necessary to override the Compare method implementation element comparison), which is equivalent to a temporary defined collation, which is actually an algorithm that injects a comparison element size through an interface, and is also an application of the callback pattern (functional programming in Java).

28. What is the meaning of how serialization is implemented in Java?
A: Serialization is a mechanism for dealing with the flow of objects, the so-called object flow, which is to stream the contents of an object. It is possible to read and write to a Fluidized object, or to transfer the streamed object between the networks. Serialization is a problem that can arise when the object stream reads and writes (if there is no serialization, there may be a problem with data scrambling).
To serialize, you need to have a class implement the Serializable interface, which is an identifying interface that annotations the class object can be serialized, and then uses an output stream to construct an object output stream and pass WriteObject (object) Method can write out the implementation object (that is, save its state), or, if deserialization is required, you can create an object input stream with an input stream and then read the object from the stream through the ReadObject method. Serialization can be used for deep cloning of objects in addition to the persistence of objects


29, briefly describe the design patterns you know.


Factory mode: Factory classes can generate different instances of subclasses based on conditions, which have a common abstract parent class and implement the same method, but these methods operate differently for different data (polymorphic methods). When an instance of a subclass is obtained, the developer can call a method in the base class without having to consider which instance of the subclass is returned.
-Proxy mode: Provides a proxy object for an object and controls the reference of the original object by the proxy object. In actual development, according to the different purposes, the agent can be divided into: Remote agent, virtual agent, protection agent, cache agent, firewall agent, synchronous agent, intelligent reference Agent.


30. What are the built-in objects of JSP? What are the roles?
A: JSP has 9 built-in objects:
-Request: Encapsulates the client's requests, which contain parameters from a GET or POST request;
-Response: Encapsulates the response of the server to the client;
-PageContext: Other objects can be obtained by this object;
-session: Encapsulates the user session object;
-Application: The object that encapsulates the server's operating environment;
-Out: Output stream object for Output server response;
-Configuration object for Config:web application;
-Page:jsp the page itself (equivalent to this in a Java program);
-Exception: Encapsulates an object that throws an exception on the page.


31. What are the differences between get and post requests?
For:
①get requests are used to obtain resources from the server, and post is used to submit data to the server;
②get adds the data in the form to the URL that the action points to by Name=value, and uses "?" for both. Connection, and the use of "&" between variables, post is the data in the form placed in the request header or message body of the HTTP protocol, passed to the URL that the action points to;
The data transmitted by ③get is subject to a URL length limit (1024 bytes), while post can transmit a large amount of data, and uploading a file usually uses the Post method;
④ parameters are displayed on the address bar when using GET, you can use get if the data is not sensitive, or use post for sensitive data or applications;
⑤get uses the format of the MIME type application/x-www-form-urlencoded URL encoding (also known as the Percent-encoded) text to pass parameters to ensure that the transmitted parameters are composed of conforming text, such as the encoding of a space is "%20".


32, explain the JSP four kinds of scopes.
A: The four scopes in the JSP include page, request, session, and application, specifically:
-the page represents the objects and properties associated with one of the pages.
-the request represents the object and property associated with one of the requests made by the Web client. A request may span multiple pages, involve multiple Web components, and temporary data that needs to be displayed on the page can be placed in this scope.
-the session represents the objects and properties associated with a session that a user has established with the server. Data related to a user should be placed in the user's own session.
-Application represents objects and properties related to the entire Web application, which is essentially a global scope that spans the entire Web application, including multiple pages, requests, and sessions

33. What is the difference between the load and get methods in hibernate session?
Answer: There are three main differences:
① if no records are found that match the criteria, the Get method returns the Null,load method throws an exception.
The ②get method returns the entity class object directly, and the Load method returns the proxy for the entity class object.
③ before Hibernate 3, the Get method only makes the data lookup in the first level cache, if the corresponding data is not found, passes through the level two cache, directly emits the SQL statement to complete the data reading; the Load method can fetch data from the two-level cache; Starting with Hibernate 3, The Get method is no longer write-only to the level two cache, and it also has access to level two cache.


34, hibernate how to realize paging query?
A: For paged queries through hibernate, developers only need to provide HQL statements (call the session's CreateQuery () method) or query conditions (call the session's Createcriteria () method), Sets the number of start rows of the query (the Setfirstresult () method that calls the query or criteria interface) and the maximum number of query rows (the Setmaxresults () method that invokes the query or criteria interface), and call the list () method of the query or criteria interface, Hibernate automatically makes the SQL statement of the Component page query


35, explain what is called AOP (aspect-oriented programming)?
A: AOP (aspect-oriented programming) refers to a programming paradigm that is based on a language construct called a facet (Aspect), which is a new modular mechanism for describing scattered objects, Crosscutting concerns in a class or method (Crosscutting concern)

36. How does Spring MVC work?
A: Spring MVC works as shown in the following:

All requests to the ① client are handled by the front-end controller Dispatcherservlet, which is responsible for invoking other modules of the system to really handle the user's request.
②dispatcherservlet receives the request, it will be based on the requested information (including URL, HTTP protocol method, request header, request parameters, cookies, etc.), and the handlermapping configuration find the handler that handles the request (any object can be the handler of the request).
③ in this place spring will encapsulate the processor through Handleradapter.
④handleradapter is an adapter that uses a unified interface to invoke methods in various handler.
After ⑤handler finishes processing the user request, it returns a Modelandview object to Dispatcherservlet,modelandview, which contains the data model and the corresponding view information.
The ⑥modelandview view is a logical view, and Dispatcherservlet also uses viewresolver to accomplish parsing from a logical view to a real view object.
⑦ when a real view object is obtained, Dispatcherservlet uses the View object to render the model data.
The ⑧ client gets a response, either as an ordinary HTML page or as an XML or JSON string, or as a picture or a PDF file.


37. Why do you choose to use the Spring framework (what are the benefits of the spring Framework for enterprise development)?
Answer: You can answer the following questions:
-Non-intrusive: Supports Pojo-based programming patterns, and does not require the implementation of interfaces in the spring framework or inheriting classes in the spring framework.
-IOC container: The IOC container helps the application manage the dependencies between objects and objects, and the dependencies between objects change only the configuration file rather than the code, because the modification of the code may imply a rebuild of the project and a complete regression test. With the IOC container, programmers no longer need to write their own factories, Singleton, which is particularly in line with spring's spirit of "Don't reinvent the wheel."
-AOP (aspect-oriented programming): Encapsulates all crosscutting concerns into facets (aspect), and dynamically adds crosscutting concerns to target code in a configured way, further separating the business logic from the system services. On the other hand, with AOP programmers can save a lot of their own job of writing proxy classes.
-Mvc:spring's MVC framework is excellent and can be flung from struts 2 of blocks in all aspects, providing a better solution for the Web presentation layer.
-Transaction management: Spring embraces multiple persistence layer technologies with a broad mind and provides declarative transaction management to complete transaction management without requiring any line of code.
-Other: The reason for choosing the spring framework is far more than that, and Spring provides a one-stop choice for Java Enterprise Development, where you can use some and all of it when you need it, and more importantly, you can even feel that spring is not there. Use the various excellent features that spring provides in your project.

38. Describe the life cycle of the bean in the spring framework?
For:
The ①spring IOC container finds a definition of the bean and instantiates the bean.
The ②spring IOC container relies on the bean for dependency injection.
③ If the bean implements the Beannameaware interface, the Bean's ID is passed to the Setbeanname method.
④ If the bean implements the Beanfactoryaware interface, the Beanfactory object is passed to the Setbeanfactory method.
⑤ If the bean implements the Beanpostprocessor interface, its Postprocessbeforeinitialization method is called.
⑥ If the bean implements the Initializingbean interface, its Afterpropertyset method is called.
⑦ If there are beanpostprocessors objects associated with the bean, the Postprocessafterinitialization method of those objects is called.
⑧ When a bean instance is destroyed, its destroy method is called if the Bean implements the Disposablebean interface.

162. How to inject the collection properties when dependency injection?
A: You can inject lists, collections, mappings, and key values into a string's mapping properties by <list>/<set>/<map>/<props> respectively when defining bean properties.

Questions on Java basic plane

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.