J'avais l'habitude de faire une série d'entretiens pour un développeur Backend Java et de noter des questions pour moi-même pour l'avenir, afin que plus tard je puisse revenir et me rafraîchir la mémoire. Je pensais que cette collection serait probablement utile non seulement pour moi, alors j'ai dépoussiéré, noté les réponses et la partager avec la communauté. Je ne prétends pas être original et exclusif: des articles similaires ont déjà été sur Habré, et dans de nombreux autres endroits - à la fin (dans la deuxième partie) je donnerai une liste de liens pour que la feuille de triche soit la plus complète possible.
— . - - middle, . . , .
Java
ArrayList
vs LinkedList
. , , — - , ArrayList , LinkedList , « » LinkedList. . , , ArrayList
System.arraycopy
, , .
HashMap
, Java.
- ( :D), JavaDoc:
- clone
- equals
- finalize (Deprecated)
- getClass
- hashCode
- toString
- notify
- notifyAll
- wait
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 :
- Young Generation
- Eden
- Survivor 0 Survivor 1
- Old Generation
- 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:
- Serial Garbage Collector
- Parallel Garbage Collector. Java 8.
- Concurrent Mark Sweep (CMS). Deprecated Java 9.
- Garbage-First (G1). Java 9. . G1 Oracle.
- Z Garbage Collector (ZGC)
- Shenandoah Garbage Collector. Java 12. , , — ,
, .
Java ", !" alygin — , , .
74 Podlodka . .
:
- Method Area — , . JVM.
- Program Counter (PC) Register — .
- Run-time Constant Pool — Method Area . , . .
- Native Method Stack — Stack .
gc JVM (, ):
- medium
- — OpenJDK
- Java Garbage Collection Handbook reachability algorithm
- Tracing garbage collection
- Simone Bordet ZGC Shenandoah
- JVM Anatomy Quarks — JVM. , , , -- .
Executor (void execute(Runnable command)
— ) ExecutorService ( , Callable ) — , . . Executors. - - , , .
:
- C
- Baeldung:
- Oracle
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 — , , . .
:
- Stream API & ForkJoinPool Fork/Join Framework Java 7
- ForkJoinPool Java 8
- Guide to the Fork/Join Framework in Java Guide to Work Stealing in Java Baeldung
- JavaDoc ForkJoinPool
- Think Twice Before Using Java 8 Parallel Streams DZone
- Java Parallel Streams Are Bad for Your Health! JRebel
- — Java Parallel Stream
- How does the Fork/Join framework act under different configurations?
- ?
2 Java Stream
:
- (Intermediate) —
filter
,map
,sorted
,peek
..Stream
. - (Terminal) —
collect
,forEach
,count
,reduce
,findFirst
,anyMatch
.. .
, java.util.stream Collectors.
- , . , , - :
Java Doc, :
- Java 8 Stream API
- The Java 8 Stream API Tutorial
- Java 8 Stream API . , !
- Java 4. Java Stream API
- Java Stream API: ,
- Spliterator
:
- letsCode — Java Stream API: , , !
- CSCenter — 8. Stream API
- Joker 2016 — Stream API
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
.
:
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
-
ConcurrentHashMap
—ConcurrentModificationException
, - (
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
— , , .
— , , .. 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-set
—current
CASset-and-get
—current
CAS ,
value
VarHandle, Unsafe, . VarHandle — , , , . , /, volotile
/ compare-and-swap
.
- AtomicBoolean, AtomicInteger, AtomicLong, AtomicIntegerArray, AtomicLongArray — , , .
- AtomicReference — .
- AtomicMarkableReference —
[reference, boolean]
. - AtomicStampedReference —
[reference, int]
. - AtomicReferenceArray —
- AtomicIntegerFieldUpdater, AtomicLongFieldUpdater, AtomicReferenceFieldUpdater — reflection.
- DoubleAccumulator, LongAccumulator — , , - (
BinaryOperator
) . , , -. - . , , . - DoubleAdder, LongAdder — , . , - , 0.
, :
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);
}
}
:
- ?
- Compare and Swap
- java.util.concurrent.*
- "Java Concurrency " —
- JDK concurrent package
- Atomic operations
- Concurrency: 6 shared state
- The Art of Multiprocessor Programming
- The JSR-133 Cookbook for Compiler Writers
- AtomicReference: A (Sometimes Easier) Alternative to Synchronized Blocks
- An Introduction to Atomic Variables in Java Bealdung
- Use AtomicReference to implement Reentrant Lock
- A comprehensive understanding of Java atomic variable classes
- Faster Atomic*FieldUpdaters for Everyone
- — Unsafe, : VarHandles
- Introduction to nonblocking algorithms
TreeMap — NavigableMap, - . Comparator, , . containsKey
, get
, put
remove
.
TreeSet — NavigableSet, TreeMap
. Comparator, , . add
, contains
remove
.
synchronized
ConcurrentModificationException.
null
, NullPointerException
. null
. 7- Java null
TreeMap
TreeSet
.
- , , , . - :
- ,
- —
:
- legacy- Java 8
- Java 8,
- Java 9+ ( 11 LTS, )
8 9 , , Java- . , , , , , , Java 8 , Java.
, :
- 9: Project Jigsaw aka , HTTP/2 Client (Incubator), jshell, G1 GC , Compact Strings .
- 10: Local-Variable Type Inference (var), Parallel Full GC G1, Graal JIT- .
- 11 LTS: var , single-file java, String, Epsilon GC (Experimental), ZGC (Experimental) .
- 12: Switch Expressions (Preview), Shenandoah (Experimental), G1, JMH
- 13: Text Blocks (Preview)
- 14: Pattern Matching instanceof (Preview), Packaging Tool (Incubator), NullPointerExceptions, Records (Preview) .
- 15: Sealed Classes (Preview), Hidden Classes, Nashorn JavaScript Engine JDK .
API, , release notes API Java-.
, , Java:
- Amber — , Java. JEP: var (JDK 10), Switch Expressions, Sealed Types, Records, Text Blocks, Pattern Matching instanceof .
- Panama — JVM . .
- Loom — Java . : .
- Valhalla — VM. : Inline types, Generics over Primitive Types, Enhanced volatiles .
- Lanai — Java- MacOS Metal Apple platform API. C 14 2020 Early-Access .
GraalVM — JDK Java, , :
- Java
- Java
- , , -
- JIT AOT-
- ..
:
- Javaswag:
- 172 Java ,
:
- Java 8-14
- API, - Java 8. 1
- JAVA 9. ?
- Java 9
- Java 9
- Java 9
- Java 10 General Availability
- Java 10
- Java 10
- Java 10
- " Java 10": Java 11
- 90 ( API) JDK 11
- Java 11: String
- Java 11 / JDK 11: General Availability
- 39 , Java 12
- Java 12! JEP-
- Java 12: The Teeing Collector
- Java 13
- Java 13 " "
- Introducing Java 13: Let's dive Into JDK's New Features
- Java 14
- Java 14 is coming
- Java 14: Record, instanceof, jpackage, switch-
- Java 14
- instanceof Java 14
- sealed Java 15
- Sealed classes. Semantics vs performance
- Sealed Java
- Java 15?
- Java 15
- Project Panama: Java " "?
- : Java. Project Loom
- Project Loom: Java
- , GraalVM
- Graal — JIT- JVM Java
- Graal: JIT- JVM
- GraalVM
- : OpenJDK-11 + GraalVM
- JavaScript, Java, ?
- GraalVM?
: - Java-
- State of Loom: 1 2
- GraalVM
:
- Cay Horstmann — Feature evolution in Java 13 and beyond
- — Java 9-14:
- — Java 9 . OSGi?
- Cay Horstmann — Java 9: the good parts (not modules)
- — Project Panama: Java “ ”?
- — GraalVM
- — Graal, Value Types, Loom
- — Java ahead of time GraalVM
- — , partial evaluation, GraalVM
- Project Loom JDK 14 letsCode
- GOTO 2019 • Life After Java 8 • Trisha Gee
- Dalia Abo Sheasha — Migrating beyond Java 8
- Project Loom: Helping Write Concurrent Applications on the Java Platform by Ron Pressler
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 pool
— heap
, . .
, [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().
: java.lang.String The Lord of the Strings: Two Scours.
:
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
- , .
:
:
byte
— 1short
— 2int
— 4long
— 8char
— 2float
— 4double
— 8
— JVM - . Java Objects Inside Out.
:
- The Java Virtual Machine Specification
- ?
- ?
- ?
- Java
- Java Objects Inside Out
- jol
- JVM ?
- Java
- Measuring Object Sizes in the JVM Bealdung
jvm ( - C++), openjdk. , , :
Java:
Strong reference
— Java. GC , ( ).- — , . :
Soft reference
— , SoftReference. GC OutOfMemoryError. ,OutOfMemoryError
.Weak reference
— , WeakReference. GC . . WeakHashMap.Phantom reference
— , PhantomReference. GC , . , ( ,finalize()
, , deprecated).
, get()
. , null
. null
.
, PhantomReference
, ReferenceQueue — , . SoftReference
WeakReference
, PhantomReference
. .
:
Spring
Spring scope:
singleton
( )prototype
request
session
application
websocket
scope
, Bealdung. , , Spring- . 2.
prototype
singleton
:
@Lookup
-
prototype
- ProxyMod = ScopedProxyMode.TARGET_CLASS
Bealdung Spring- . 2.
-, spring-boot-starter-parent, spring-boot-dependencies, — , dependencyManagement
pom. BOM.
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.factories — org.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-Class
— org.springframework.boot.loader.JarLauncher, Start-Class
main- . JarLauncher
class path ( org.springframework.boot
), BOOT-INF
( lib
class
), Start-Class
.
:
- Boot yourself, Spring is coming: 1, 2. : 1, 2.
- Spring Boot Starter — ?
- — Spring Boot Starter
:
- : Spring Boot Auto-Configuration, spring-boot-starter Conditional Spring
- H Baeldung: A Comparison Between Spring and Spring Boot, Create a Custom Auto-Configuration with Spring Boot, Intro to Spring Boot Starters, Spring Boot: Configuring a Main Class
- What is Spring Boot? Autoconfigurations In-Depth
- Spring Boot for beginners
- Spring Boot Documentation
Spring -:
- Spring MVC
- Spring WebFlux
Spring MVC DispatcherServlet, Servlet
' Front Controller: Http- . DispatcherServlet
WebApplicationContext. DispatcherServlet
" " :
- HTTP-
DispatcherServlet
( ) HandlerMapping, ,Controller
.HandlerMapping
, : BeanNameUrlHandlerMapping RequestMappingHandlerMapping ( RequestMappingInfo @RequestMapping @Controller).HandlerMapping
HttpServletRequest — handler- (, HandlerMethod).HandlerMapping
HandlerInterceptor — - .HandlerInterceptor
' handler- HandlerExecutionChain,DispatcherServlet
. - HandlerAdapter . HttpRequestHandlerAdapter ( , HttpRequestHandler), SimpleControllerHandlerAdapter ( , Controller) RequestMappingHandlerAdapter (
@RequestMapping
). -
applyPreHandle
HandlerExecutionChain
.true
,HandlerInterceptor
.false
,HandlerInterceptor
. -
HandlerAdapter
HandlerExecutionChain
handle
, - . - -
Controller
(handle
)DispatcherServlet
ModelAndView. ViewResolverDispatcherServlet
, View .
REST-Controller RESTful- ,ModelAndView
DispatcherServlet
Controller
null
, ,ViewResolver
— HttpServletResponsehandle
. RESTful-, @ResponseBody@Controller
@RestController, RESTful. -
HandlerExecutionChain
applyPostHandle
HandlerInterceptor
. - , HandlerExceptionResolver. ExceptionHandlerExceptionResolver ( , @ExceptionHandler), ResponseStatusExceptionResolver ( @ResponseStatus HTTP-) DefaultHandlerExceptionResolver ( Spring MVC HTTP-).
-
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 MVC —
- Spring Security
- An Intro to the Spring DispatcherServlet Bealdung
- HandlerAdapters in Spring MVC Bealdung
- Quick Guide to Spring Controllers Bealdung
- Spring RequestMapping Bealdung
- Http Message Converters with the Spring Framework Bealdung
- How to Define a Spring Boot Filter? Bealdung
- Spring Professional Study Notes
- Spring Security Architecture
:
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));
}
- HandlerMapping (- , - ). (
handler
).HandlerMapping
:
- RequestMappingHandlerMapping -,
@RequestMapping
- RouterFunctionMapping
- SimpleUrlHandlerMapping URL- -
- RequestMappingHandlerMapping -,
- , (
invokeHandler
) HandlerAdapter,handle
. HandlerResult,DispatcherHandler
.HandlerAdapter
— -DispatcherHandler
.HandlerAdapter
:
- RequestMappingHandlerAdapter — ,
@RequestMapping
- HandlerFunctionAdapter — HandlerFunctions
- RequestMappingHandlerAdapter — ,
-
HandlerResult
(handleResult
) HandlerResultHandler. .HandlerResultHandler
:
- ResponseEntityResultHandler — ResponseEntity,
@Controller
- ServerResponseResultHandler — ServerResponse,
- ResponseBodyResultHandler — ,
@ResponseBody
,@RestController
- ViewResolutionResultHandler — View Resolution
- ResponseEntityResultHandler — ResponseEntity,
:
Dans la deuxième partie, nous parlerons d'Hibernate, des bases de données, des modèles et pratiques de développement, d'une bibliothèque populaire, du support et de la maintenance de nos applications, et nous examinerons également les feuilles de triche alternatives et les résumerons.