I used to do a series of interviews for a Backend Java developer and jot down questions for myself for the future, so I could go over and refresh my memory later. I thought that this collection will probably be useful not only for me, so I blew the dust off it, jotted down the answers and share it with the community. I do not pretend to be original and exclusive: similar articles have already been on HabrΓ©, and in many other places - at the end (in the second part) I will give a list of links so that the cheat sheet is as complete as 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 β , 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.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,
:
In the second part, we 'll talk about Hibernate, databases, development patterns and practices, one popular library, support and maintenance of our applications, and also look at alternative cheat sheets and summarize.