First-line internet common 14 Java interview questions, do you tremble? Programmer

Source: Internet
Author: User
Tags export class finally block instance method message queue volatile

Job-hopping is not frequent, but has participated in a lot of interviews (telephone interview, face to faces interview), large/small companies, Internet/traditional software company, batter (above his business, lack of actual combat experience, hang off), also face, fortunately not because of failure and discouraged, in the process of constantly check gaps, developed a practical, Trace, continuous improvement of the habit, I have experienced, conceived some of the questions recorded, if the answer is a problem, welcome to the brick discussion, hoping to find a job or interested students have some help, and finishing in succession.

1. Similarities and differences between synchronized and Reentrantlock

Same point

    • Implement multi-threaded synchronization and memory visibility semantics

    • Are all reentrant locks

Different points

  • Implementation mechanism is different synchronized through the Java Object Header lock tag and Monitor object implementation Reentrantlock through
    CAS, ASQ (Abstractqueuedsynchronizer), and Locksupport (for blocking and unblocking) implementations
    Synchronized relies on the JVM memory model to guarantee multi-threaded memory visibility with shared variables Reentrantlock through ASQ's
    Volatile State guarantees multi-threaded memory visibility with shared variables

  • Use different synchronized can decorate instance method (lock instance object), static method (lock class object), code block (display specified lock object) Reentrantlock Show Call Trylock ()/lock () method, need to release lock in finally block

  • Different feature richness Reentrantlock
    Provides a limited time to wait for a lock (set expiration time), interruptible Lock (lockinterruptibly), condition (provides await, signal
    and other methods) such as rich semantic reentrantlock provide fair lock and non-fair lock implementation synchronized
    Cannot set wait time, cannot be interrupted (interrupted)

2. Why Concurrenthashmap read without locking

jdk1.7

    • 1) The key, hash, and next in the Hashentry are final and can only be inserted by the table header , delete node

    • 2) The Value field of the Hashentry class is declared as volatile

    • 3) does not allow NULL as a key and value when read threads read to the value of a hashentry When the value of the field is null
      , it is known that there was a conflict-a reordering occurred (put to reorder the bytecode of the new value object), which needed to be re-read into this value value

    • 4) volatile variable count coordinated read Memory visibility between write threads, modify count after write operation, read first count, see

    as modified by the
    Happen-before transitive principle write operation

jdk1.8

    • 1) Node's Val and next are volatile type

    • 2) the Tabat and castabat corresponding unsafe operations implement the volatile semantics

3. The role of the Contextclassloader (thread context ClassLoader)
    • Go beyond the parent delegation mechanism of the ClassLoader to load classes, such as Serviceloader implementations

    • Using the thread context class loader to load classes, it is important to ensure that the class loader between multiple threads that need to communicate should be the same, preventing the type conversion exception from being caused by different classloader (classcastexception)

4. Tomcat class loading mechanism

    • Different applications use different WebApp class loaders to achieve the effect of application isolation, and the WebApp class loader below is the JSP ClassLoader

    • Jar packages shared by different applications can be placed in the shared ClassLoader/shared directory

5. OSGi class loading mechanism

    • The OSGi class loading model is meshed and can be delegated to each other between modules (bundles)

    • OSGi The key to implementing a modular thermal deployment is the implementation of a custom classloader mechanism, with each bundle having its own classloader that, when a bundle needs to be replaced, replaces the bundle with the same loader to implement hot replacement of the code

When a class load request is received, OSGi will perform a class search in the following order:

  • 1) Delegate the class beginning with java.* to the parent ClassLoader load

  • 2) Otherwise, delegate the class within the delegated list (defined in profile org.osgi.framework.bootdelegation) to the parent ClassLoader load

  • 3) Otherwise, check whether the declaration is declared in Import-package, and if so, the class loader that is delegated to the Bundle of the Export class loads

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

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

  • 6) Otherwise, the lookup class is in its own Fragment bundle, and if so, the class loader delegated to the Fragment bundle loads

  • 7) Otherwise, find the dynamic import-package (dynamic Import only in the real use of this package
    To load the bundle, delegating to the corresponding bundle's class loader

  • 8) Otherwise, the class lookup fails

6. How to end a running thread
    • Using the exit flag, this flag variable is visible to multiple threads

    • Use interrupt, combined with isinterrupted ()

7. Threadlocal Usage Scenarios and issues
  • Threadlocal does not solve the problem of multi-threaded shared variables, the same threadlocal contains objects in different thread
    There are different copies of each other, non-interference

  • Used to store thread context variables to facilitate multiple reads of variables, such as transactions, database connection connections, and more in web programming

  • issue : Note that thread pool scenarios use threadlocal because the actual variable values are stored in the thread's Threadlocalmap
    Type variable, if the value does not have a remove, and there is no first set, the previous old value may be obtained

  • issue : Note the memory leaks in the thread pool scenario, although Threadlocal's Get/set clears the key (key is a weak reference to threadlocal, value is a strong reference and causes value not to be freed) to be null entry, but is the best remove

8. The process of thread pooling from boot to work

There are no threads in the first creation
When you call execute () to add a task:

  • 1) If the number of threads running is less than the core parameter corepoolsize, continue creating the thread to run this task

  • 2) Otherwise, if the number of running threads is greater than or equal to Corepoolsize, the task is added 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 creating the thread 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, processing according to the denied policy set

  • 5) Complete a task, continue to remove a task processing

  • 6) No task continues processing, thread is interrupted, or thread pool is closed, threads exit execution if thread pool is closed, threads end

  • 7) Otherwise, determine if the thread pool is running more threads than the number of core threads, and if so, the thread ends, otherwise the thread is blocked. So after all the thread pool tasks are complete, the thread pool size that continues to be retained is corepoolsize

  • 8) The 14 Java test questions listed in this article are just a part of the interview I encountered, and the other side of the question I will be sorted out, said here in addition to recommend an architecture Exchange Learning Group: 650385180, which will share some senior architect recorded video recording: There is spring, Mybatis,netty source code Analysis, high concurrency, performance, distributed, micro-service architecture, JVM performance optimization These become the necessary knowledge system for architects. can also receive free learning resources, I believe for already work and meet the technical bottleneck of the Code friends, in this group will have you need content.

9. Blocking queue Blockingqueue take and poll differences
    • Poll (time): Take the first object in the Blockingqueue, if it cannot be removed immediately, you can wait for the times specified in the parameters, and return NULL when not taken.

    • Take (): Takes the first object in the Blockingqueue, if Blockingqueue is empty, blocks until blockingqueue new object is added

10. How to get results without blocking from Futuretask
    • Get (long timeout,timeunit unit), which time out returns

    • Polling, first through IsDone () to determine whether to end, and then call Get ()

Blockingqueue How to handle a system outage if it holds more critical data
    • Open question, welcome to discuss

    • Persist the queue, be troublesome, need to persist the production data to disk, persist the success to return, the consumer thread loads the data from the disk to the memory Jam queue, maintains the consumption offset, starts, loads the data from the disk according to the consumption offset

    • Join the message queue, ensure that the message is not lost, generate serial number, power consumption, etc., according to the consumption process to determine the system restart production status

The difference between NIO and traditional I/O
    • Saving threads, NIO by the original each thread needs to block read and write into a single thread (i.e., Selector) responsible for processing multiple channel
      Register (Register) interest Event (Selectionkey) collection (bottom-level with OS-provided Epoll ()), Netty Bossgroup handles the Accept connection (the need to see why Bossgroup set multiple thread) , Workergroup handles specific business processes and data reads and writes

    • NIO provides non-blocking operations

    • Traditional I/O processes the data in a stream, and NIO processes the data in chunks, and NiO provides Bytebuffer, which is divided into heap and out-of-stack buffers, which are first placed in the buffer, and then transmitted by the kernel to the peer through the channel, which improves performance by not taking the kernel out of the heap.

A repeating string is stored in list, how to delete a string
    • Call Iterator Related method delete

    • Inverted delete prevents the array rearrangement caused by the positive sequence deletion, the index skips several group element problems

14. What GC ROOTS (relative to the daily development is associated with this memory leak)
    • All Java threads currently active in the stack frame refer to the objects in the GC heap, so the objects that are not available are NULL in time, improving the efficiency of memory reclamation

    • Static variables refer to objects, thus reducing the size of static variables, especially static set variables, the objects that are stored in the collection overwrite Euqls () and hashcode () to prevent continuous growth

    • Objects referenced by local method JNI

    • The constants in the method area refer to the object, thus reducing the call to String.intern () on a long string

    • ClassLoader loaded class object, so the custom ClassLoader is invalid when null is placed and notice the isolation between the ClassLoader loading objects

    • References to objects in the GC heap in some static data structures in the JVM

    • ...


First-line internet common 14 Java interview questions, do you tremble? Programmer

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.