Home >Java >JavaInterview questions >14 common Internet Java interview questions

14 common Internet Java interview questions

(*-*)浩
(*-*)浩Original
2019-11-15 16:31:282461browse

14 common Internet Java interview questions

1.Synchronized and reentrantlock similarities and differences

Same points

Both implement multi-thread synchronization and memory visibility semantics, and are all reentrant locks

Differences

The implementation mechanisms are different. Synchronized through java object head lock mark and Monitor The object implements reentrantlock and implements synchronized through CAS, ASQ (AbstractQueuedSynchronizer) and locksupport (for blocking and unblocking). It relies on the jvm memory model to ensure the visibility of multi-threaded memory containing shared variables. reentrantlock ensures multi-threaded memory containing shared variables through ASQ's volatile state. Visibility

Used in different ways, synchronized can modify instance methods (lock instance objects), static methods (lock class objects), code blocks (display specified lock objects), reentrantlock, and display calls to trylock()/lock() method, the lock needs to be released in the finally block. The richness of the function is different. reentrantlock

provides rich semantics such as limited time waiting for the lock (setting the expiration time), interruptible lock (lockInterruptibly), condition (providing await, signal and other methods). reentrantlock provides fair locks and unfair locks to implement synchronized, which cannot set the waiting time and cannot be interrupted.

2. Why does concurrenthashmap read without locking?

jdk1.7

1) The key, hash, and next in HashEntry are all final type, and only the header can be inserted or deleted.

2) The value field of the HashEntry class is declared as volatile

3) It is not allowed to use null as the key and value. When the reading thread reads that the value of the value field of a HashEntry is null, it knows that a conflict has occurred - a reordering phenomenon has occurred (put sets a new value object Reordering of bytecode instructions), you need to re-read this value after locking

4) The volatile variable count coordinates the memory visibility between read and write threads. The count is modified after the write operation, and the read operation first Read count, according to the happened-before transitivity principle, the modified read operation of the write operation can be seen

jdk1.8

1) Node's val and next are both volatile

2) The unsafe operations corresponding to tabAt and casTabAt implement volatile semantics

3. The role of ContextClassLoader (thread context class loader)

Override the parents of the class loader Delegation mechanism to load classes, such as serviceloader implementation, uses thread context class loader to load classes. Pay attention to ensure that the class loader between multiple threads that need to communicate should be the same to prevent type conversion exceptions (ClassCastException) caused by different class loaders. )

4. Tomcat class loading mechanism

Different applications use different webapp class loaders to achieve the effect of application isolation. Below the webapp class loader is the jsp class loading server; jar packages shared by different applications can be placed in the Shared class loader/shared directory

5. osgi class loading mechanism

osgi class loading model is mesh Yes, you can delegate each other between modules (Bundle)

osgi The key to realizing modular hot deployment is the implementation of the custom class loader mechanism. Each Bundle has its own class loader, which can be replaced when it needs to be replaced. When a Bundle is loaded, the Bundle and the class loader are replaced together to achieve hot replacement of the code

When receiving a class loading request, osgi will perform a class search in the following order:

1) Delegate classes starting with java.* to the parent class loader for loading

2) Otherwise, delegate classes in the delegation list (defined in the configuration file org.osgi.framework.bootdelegation) to the parent Class loader loading

3) Otherwise, check whether it is declared in the Import-Package. If so, the class loader of the Bundle delegated to Export this class is loaded

4) Otherwise, check Whether it is declared in Require-Bundle, if so, delegate the class loading request to the class loader of the required bundle

5) Otherwise, find the ClassPath of the current Bundle and use your own class loader to load it

6) Otherwise, look for whether the class is in its own Fragment Bundle. If so, delegate it to the class loader of the Fragment Bundle to load

7) Otherwise, look for the Dynamic Import-Package (Dynamic Import is only available in The Bundle is loaded only when this Package is actually used) and is delegated to the class loader of the corresponding Bundle for loading

8) Otherwise, the class search fails

6. How to end a Threads that are always running

Use the exit flag. This flag variable must be visible to multiple threads

Use interrupt, combined with isInterrupted()

7. threadlocal Usage scenarios and problems

threadlocal cannot solve the problem of multi-thread shared variables. Objects contained in the same threadlocal have different copies in different threads without interfering with each other

Used to store thread context variables to facilitate multiple readings of variables by the same thread, such as transactions and database connection connections. More

issues used in web programming: Note that thread pool scenarios use threadlocal. Because the actual variable value is stored in the threadlocalmap type variable of thread, if the value is not removed or set first, the old value may be obtained

Question: Pay attention to the memory leak in the thread pool scenario. Although the get/set of threadlocal will clear the entry with key (key is a weak reference of threadlocal, value is a strong reference, causing the value not to be released), but it is best to remove it.

8. The process of thread pool from startup to work

When it is first created, there is no thread in it to call execute(). When adding a task:

1 ) If the number of running threads is less than the core parameter corePoolSize, continue to create threads to run this task

2) Otherwise, if the number of running threads is greater than or equal to corePoolSize, add the task to the blocking queue

3) Otherwise, if the queue is full and the number of threads running at the same time is less than the core parameter maximumPoolSize, continue to create threads to run this task

4) Otherwise, if the queue is full and the number of threads running at the same time is greater than Or equal to maximumPoolSize, processed according to the set rejection policy

5) Complete a task and continue to process the next task

6) When there is no task to continue processing, the thread is interrupted or the thread pool is closed , the thread exits execution, if the thread pool is closed, the thread ends

7) Otherwise, determine whether the number of threads running in the thread pool is greater than the number of core threads, if so, the thread ends, otherwise the thread blocks. Therefore, after all thread pool tasks are executed, the size of the thread pool that continues to remain is corePoolSize

9. The difference between blocking queue BlockingQueue take and poll

poll(time): take Take the first object in the BlockingQueue. If it cannot be taken out immediately, you can wait for the time specified by the time parameter. If it cannot be obtained, it will return null

take(): Take the first object in the BlockingQueue. If BlockingQueue is empty, blocking until new objects are added to BlockingQueue

10. How to get results from FutureTask without blocking

get(long timeout,TimeUnit unit), timeout Then return to

Polling, first use isDone() to determine whether it is finished, and then call get()

11. blockingqueue What to do if the system crashes if critical data is stored Processing

Persisting the queue is troublesome. The production data needs to be persisted to the disk. It will be returned only after the persistence is successful. The consumer thread loads the data from the disk into the memory blocking queue and maintains the consumption offset. At startup, data is loaded from disk and added to the message queue according to the consumption offset to ensure that messages are not lost, sequence numbers are generated, consumption is idempotent, and the production status after system restart is determined based on the consumption process

12. NIO and The difference between traditional I/O

Save threads, NIO changes from the original need for each thread to block reading and writing to a single thread (ie Selector) responsible for processing multiple channel registrations (register) Collection of interest events (SelectionKey) (the bottom layer relies on epoll() provided by the operating system), netty bossgroup handles accept connections, workergroup handles specific business processes and data reading and writing, NIO provides non-blocking operations, traditional I/O processes data in a streaming manner, and NIO processes data in blocks. NIO provides bytebuffer, which is divided into in-heap and off-heap buffers. When reading and writing, they are first placed in this buffer, and then the kernel transmits it to the opposite end through the channel. The off-heap buffer is not removed. Kernel, improved performance

13. Repeatable strings are stored in the list, how to delete a certain string

Call iterator related methods to delete backward deletion and prevent positive sequence Array rearrangement caused by deletion, index skipping array elements problem

14. What are the GC ROOTS (more relevant to daily development are memory leaks related to this)

The currently active stack frames of all Java threads point to references to objects in the GC heap, so unused objects are set to null in time to improve memory recycling efficiency

Objects referenced by static variables, so static variables are reduced Especially the size of static collection variables, the objects stored in the collection overwrite euqls() and hashcode() to prevent continuous growth

Objects referenced by local methods JNI

Constant references in the method area Object, therefore reducing the need to call String.intern() on long strings

Class objects loaded by classloader, therefore when the custom classloader is invalid, set null in time and pay attention to the isolation between objects loaded by the class loader in jvm Some static data structures point to references to objects in the GC heap

The above is the detailed content of 14 common Internet Java interview questions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn