Entrevista al desarrollador de backend Java: preguntas y dónde buscar respuestas. Parte 1



Solía ​​hacer una serie de entrevistas para un desarrollador de Backend Java y anotar preguntas para mí mismo para el futuro, para poder ir y refrescar mi memoria más tarde. Pensé que esta colección probablemente sería útil no solo para mí, así que le soplé el polvo, anoté las respuestas y las compartí con la comunidad. No pretendo ser original y exclusivo: ya se han publicado artículos similares en Habré, y en muchos otros lugares - al final (en la segunda parte) daré una lista de enlaces para que la hoja de trucos sea lo más completa posible.



— . - - middle, . . , .



, . Java Spring, — .



TL;DR

GitHub- , .





Java



1. Equals, hashcode HashMap.

. HashMap. ? ? , , . — ? , , ? . . . .



equals hashcode:



  1. .
  2. equals, .
  3. , equals ().
  4. , .


, - .



HashMap ( , Java 8, - ). , IDE. :)



2. : , , , , .

ArrayList vs LinkedList. , , — - , ArrayList , LinkedList , « » LinkedList. . , , ArrayList System.arraycopy, , .



3. `Object`.

HashMap, Java.



- ( :D), JavaDoc:



  • clone
  • equals
  • finalize (Deprecated)
  • getClass
  • hashCode
  • toString
  • notify
  • notifyAll
  • wait


, Object .



4. `wait`, `notify`, `notifyAll` `synchronized`.

, Baeldung . , , wait, notify, notifyAll synchronized . Oracle Concurrency Java.

, — . Java Language Specification, 17.1 17.2.



5. JMM. volatile. .

, JMM — , , . , , — , .



, JMM.



, JMM. , . ". Java- ": 1 2.



Java Language Specification, 17.4.



itsobes.ru.

JVM- How ‘volatile’ works on JVM level? Medium.



6. . ? ? JVM? , , - ?

Java Stack Heap.



Stack — , LIFO. frame — . , , , Heap. , Escape Analysis Java 6, , , . Escape Analysis ( ) , .



Frame Stack . Frame , , , . Stack . JVM Specification.



Heap . , telegram- Senior's Blog. :



Heap :



  1. Young Generation

    1. Eden
    2. Survivor 0 Survivor 1


  2. Old Generation

    1. Tenured






Young : Eden, Survivor 0 Survivor 1. Eden . Survivor . Eden , Eden Survivor Survivor, Eden Survivor . . , Survivor, Tenured.



, Tenured, , . , . Tenured ( ), , , . Mark-Sweep-Compact ( , , ).



-, , Eden, Survivor’ . Tenured.



, , , . Survivor , Eden .

GC:





, .

Java ", !" alygin, , .

74 Podlodka . .



:





gc JVM (, ):



  • medium
  • — OpenJDK
  • Java Garbage Collection Handbook reachability algorithm
  • Tracing garbage collection
  • Simone Bordet ZGC Shenandoah
  • JVM Anatomy Quarks — JVM. , , , -- .


7. Executor ExecutorService, Thread pool ?

— . N (Thread pool) . . .



Executor (void execute​(Runnable command) — ) ExecutorService ( , Callable ) — , . . Executors. - - , , .



:



  • C
  • Baeldung:
  • Oracle


8. Java ? ? heap-dump?

. . heap-dump, jmap, memory profiler ( VisualVM)



:





9. ? ?

parallel stream ForkJoinPool.commonPool Runtime.getRuntime().availableProcessors() — 1. Common pool ForkJoinPool System::exit ( shutdown() shutdownNow()). common pool, pool . Common pool . stream ForkJoinPool — stream Callable submit ForkJoinPool. fork() ForkJoinPool ( ).



ForkJoinPool ExecutorService, ForkJoinTask (RecursiveAction RecursiveTask). pool . ForkJoinPool work stealing — , , . .



:





10. ? ?

2 Java Stream:



  • (Intermediate) — filter, map, sorted, peek .. Stream.
  • (Terminal) — collect, forEach, count, reduce, findFirst, anyMatch .. .


, java.util.stream Collectors.



- , . , , - :





Java Doc, :





:





11. List<? extends Number>, List<? super Number>? , , ?

PECS — Producer extends, Consumer super (Joshua Bloch, Effective Java). — (, , ).



(covariance) — .

List<? extends T> , T , . List<? extends T> ( null) — , , . , T T, T.

, List<? extends Number> ArrayList<Number> ArrayList<Integer>, ArrayList<Object>. get Number, Integer Number.

.

, Java 5, .



List<?> List<? extends Object> .



(contravariance) — .

List<? super T> , T , . List<? super T> T , T . Object, .

, List<? super Number> ArrayList<Number>, ArrayList<Object>, Number(.. ArrayList<Integer>). Integer Double ( Number, ), — Object. get Object — .



— .

List<T> , T. T . T, .

, List<Number> ArrayList<Number>, ArrayList<Integer> ArrayList<Object>. Integer Double ( Number, ), — Object. get Number, Integer Number.



:





12. ConcurrentHashMap?

ConcurrentHashMap — (, , , ""), .

:



  • (Node<K,V>) val () next( ), (Node<K,V>[] table) volatile
  • CAS — , (insert, delete, replace)
  • volatile/atomic , CAS, intrinsics- (jdk.internal.misc.Unsafe)
  • Concurrent resizing
  • LongAdder


:



  • . , non-null , get(key) happens-before
  • ConcurrentHashMapConcurrentModificationException,
  • (size, isEmpty, containsValue),
  • null,
  • , ( ) , — forEach, search, reduce (bulk operations). , - ( forEach). parallelismThreshold — , parallelismThreshold. Long.MAX_VALUE . 1 ForkJoinPool.commonPool(),


— java 8 . Segment<K,V> , . concurrencyLevel initialCapacity - :



if (initialCapacity < concurrencyLevel)   // Use at least as many bins
    initialCapacity = concurrencyLevel;   // as estimated threads


ConcurrentMap. ConcurrentMap Baeldung.



13. Xmx Xms, Xss?

JVM Xms heap Xmx.

Xss .

:



java -Xmx<>< >


, (k), (m) (g).

:



java -jar my.jar -Xms256m -Xmx2048m


:



  • Mkyong
  • Tuning JVM Orcale
  • Factors Affecting Garbage Collection Performance Oracle
  • X CLI


14. ?

— , , .

— , , .. lock-free thread-safe . compare-and-swap (CAS) , . CAS.



. volatile value, compareAndSet(current, new), — current. CAS value , (.. current), compareAndSet(current, new). value , . , compareAndSet false. compareAndSet(current, new) current value.



:



  • compare-and-setcurrent CAS
  • set-and-getcurrent CAS ,


value VarHandle, Unsafe, . VarHandle — , , , . , /, volotile / compare-and-swap.



java.util.concurrent.atomic :





, :



public class NonReentrantSpinLock {

    private AtomicReference<Thread> owner = new AtomicReference<>();

    public void lock() {
      Thread currentThread = Thread.currentThread();

      while (!owner.compareAndSet(null, currentThread)) {}
    }

    public void unlock() {
      Thread currentThread = Thread.currentThread();
      owner.compareAndSet(currentThread, null);
    }
}


:





15. TreeSet/TreeMap? - ?

TreeMapNavigableMap, - . Comparator, , . containsKey, get, put remove.

TreeSetNavigableSet, TreeMap. Comparator, , . add, contains remove.



synchronized ConcurrentModificationException.



null, NullPointerException. null . 7- Java null TreeMap TreeSet .



- , , , . - :



  • ,


:





16. Java 8 Java <CURRENT_VERSION>?

Java . :



  • legacy- Java 8
  • Java 8,
  • Java 9+ ( 11 LTS, )


8 9 , , Java- . , , , , , , Java 8 , Java.



, :





API, , release notes API Java-.



, , Java:





GraalVM — JDK Java, , :



  • Java
  • Java
  • , , -
  • JIT AOT-
  • ..


:





:





:





17. Java? String? String?

Java 9 UTF-16 (2 ) char.

Java 9 Compact String. Latin-1 ( ), 1 , char . char byte, Latin-1 . byte coder, Latin-1 UTF-16.



String hashcode.



, (final class). , . StringBuilder append. ! Java 9 JEP 280: Indify String Concatenation, . StringBuilder bytecode StringConcatFactory invokedynamic, +.



String poolheap , . .



, [String.intern()](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/String.html#intern()) , . . — JVM Anatomy Quark #10: String.intern().



, equals ( indexOf) JIT .



: java.lang.String The Lord of the Strings: Two Scours.



:





18. ThreadLocal ?

ThreadLocal — , .



ThreadLocal- , Thread. Thread ThreadLocal.ThreadLocalMap threadLocals, ThreadLocal. ThreadLocal.ThreadLocalMap HashMap, WeakReference<ThreadLocal<?>>, ref field . ThreadLocal, — Object. null, (stale) .

, ThreadLocal , . , .

ThreadLocal- ( get), , threadLocals, , . ThreadLocal.

, ThreadLocal- , .



:





19. ? ?

:



  • byte — 1
  • short — 2
  • int — 4
  • long — 8
  • char — 2
  • float — 4
  • double — 8


boolean . — , . JVM. .



— JVM - . Java Objects Inside Out.



:





jvm ( - C++), openjdk. , , :





20. Java?

Java:





, get(). , null. null.



, PhantomReference , ReferenceQueue — , . SoftReference WeakReference , PhantomReference . .



:





Spring



21. scope Spring? ? singleton prototype? scope ? ' prototype singleton?'

Spring scope:



  • singleton ( )
  • prototype
  • request
  • session
  • application
  • websocket


scope , Bealdung. , , Spring- . 2.



prototype singleton :



  • @Lookup
  • prototype-
  • ProxyMod = ScopedProxyMode.TARGET_CLASS

    Bealdung Spring- . 2.


22. Spring. ? , ?

, — BeanCurrentlyInCreationException ( ).



:



  • , —
  • @Lazy
  • setter-,


Bealdung



23. , , , DI

Spring- 1 2. — .



.



24. @Transactional. ? ? @Transactional ? @Transactional @Transactional - ?

, Proxy , .



, MyServiceImpl 2 , @Transactionalmethod1 method2( Propagation.REQUIRES_NEW). method1 method2.



, Spring AOP, method1() . method1() MyServiceImpl. method1() method2(), , , , .

, .



? Spring- — 1 2. Proxy .



25. ( Boot) Spring- main-?

Spring- ( ), main-. war-. war- , , . Spring Boot war .



:





26. Spring Boot ?

-, spring-boot-starter-parent, spring-boot-dependencies, — , dependencyManagement pom. BOM.



Spring Boot — , properties-.



Spring Boot main- @SpringBootApplication run SpringApplication, ApplicationContext.



@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}


@SpringBootApplication @EnableAutoConfiguration, @ComponentScan @Configuration.



SpringBootApplication WebApplicationContext ( classpath Servlet ConfigurableWebApplicationContext), GenericApplicationContext.



META-INF/spring.factoriesorg.springframework.boot.autoconfigure.EnableAutoConfiguration - ( , @ComponentScan, @Import ..) .



@EnableAutoConfiguration AutoConfigurationImportSelector, . getCandidateConfigurations SpringFactoriesLoader loadFactoryNames, classpath META-INF/spring.factories - , .



Spring boot spring-boot-autoconfigure META-INF/spring.factories. - , @Conditional ( ) - .



Spring boot jar spring-boot-maven-plugin. jar META-INF/MANIFEST.MF Main-Classorg.springframework.boot.loader.JarLauncher, Start-Class main- . JarLauncher class path ( org.springframework.boot), BOOT-INF( lib class ), Start-Class.



:





:





27. http- Spring?

Spring -:



  • Spring MVC
  • Spring WebFlux


Spring MVC DispatcherServlet, Servlet' Front Controller: Http- . DispatcherServlet WebApplicationContext. DispatcherServlet " " :



  1. HTTP- DispatcherServlet ( ) HandlerMapping, , Controller . HandlerMapping, : BeanNameUrlHandlerMapping RequestMappingHandlerMapping ( RequestMappingInfo @RequestMapping @Controller). HandlerMapping HttpServletRequest — handler- (, HandlerMethod). HandlerMapping HandlerInterceptor- . HandlerInterceptor' handler- HandlerExecutionChain, DispatcherServlet.
  2. HandlerAdapter . HttpRequestHandlerAdapter ( , HttpRequestHandler), SimpleControllerHandlerAdapter ( , Controller) RequestMappingHandlerAdapter ( @RequestMapping).
  3. applyPreHandle HandlerExecutionChain. true, HandlerInterceptor . false , HandlerInterceptor .
  4. HandlerAdapter HandlerExecutionChain handle , - .
  5. - Controller ( handle) DispatcherServlet ModelAndView. ViewResolver DispatcherServlet , View .

    REST-Controller RESTful- , ModelAndView DispatcherServlet Controller null , , ViewResolverHttpServletResponse handle. RESTful-, @ResponseBody @Controller @RestController, RESTful.
  6. HandlerExecutionChain applyPostHandle HandlerInterceptor.
  7. , HandlerExceptionResolver. ExceptionHandlerExceptionResolver ( , @ExceptionHandler), ResponseStatusExceptionResolver ( @ResponseStatus HTTP-) DefaultHandlerExceptionResolver ( Spring MVC HTTP-).
  8. Controller , View , DispatcherServlet View, HttpServletResponse. REST-Controller , HttpServletResponse.


HTTP Accept, Spring MVC HttpMessageConverter , , POJO Accept. HttpMessageConverter : Java , Java HTTP .

, Spring Boot HttpMessageConverter, , HttpMessageConverter .



, , Spring MVC javax.servlet.Filter , . Sring MVC .



Spring Security, . .



:





:





Spring WebFlux — -, Spring Framework 5.0. Servlet API ( Servlet 3.1+containers, Netty ( Spring Boot) Undertow), , Reactive Streams Reactor.

Spring WebFlux Spring MVC (RestController, RequestMapping ) . , HandlerFunction.



Spring WebFlux :



  • HttpHandler — HTTP- I/O, Reactive Streams back pressure Reactor Netty, Undertow ..
  • WebHandler — , API HTTP- .


HttpHandler HTTP-, WebExceptionHandler, WebFilter WebHandler. WebHttpHandlerBuilder ApplicationContext.



Spring WebFlux DispatcherHandler, WebHandler Front Controller: Http- . DispatcherHandler — Spring bean, ApplicationContextAware , . DispatcherHandler - webHandler WebHttpHandlerBuilder WebHandler.



DispatcherHandler http- " ", , . :



    @Override
    public Mono<Void> handle(ServerWebExchange exchange) {
        if (this.handlerMappings == null) {
            return createNotFoundError();
        }
        return Flux.fromIterable(this.handlerMappings)
                .concatMap(mapping -> mapping.getHandler(exchange))
                .next()
                .switchIfEmpty(createNotFoundError())
                .flatMap(handler -> invokeHandler(exchange, handler))
                .flatMap(result -> handleResult(exchange, result));
    }


  1. HandlerMapping (- , - ). (handler). HandlerMapping :

  2. , ( invokeHandler) HandlerAdapter, handle . HandlerResult, DispatcherHandler. HandlerAdapter — - DispatcherHandler. HandlerAdapter :

  3. HandlerResult ( handleResult) HandlerResultHandler. . HandlerResultHandler:



:







En la segunda parte, hablaremos sobre Hibernate, bases de datos, patrones y prácticas de desarrollo, una biblioteca popular, soporte y mantenimiento de nuestras aplicaciones, y también veremos hojas de trucos alternativas y resumiremos.




All Articles