Skip to main content
Interview Toolkit · Topic 6 of 6

Cheat Sheets

Dense reference tables for the day before an interview. Each section links to the full explanation; if a line surprises you, read that page.

How it works​

Collections: complexity at a glance​

Structureget / containsaddremoveOrderNullThread-safe
ArrayListO(1) idx / O(n)O(1) amortised endO(n)InsertionYesNo
LinkedListO(n)O(1) endsO(1) at nodeInsertionYesNo
ArrayDequeO(1) endsO(1)O(1) endsInsertionNoNo
HashMap / HashSetO(1) avgO(1) avgO(1) avgNone1 null keyNo
LinkedHashMapO(1)O(1)O(1)Insertion / accessYesNo
TreeMap / TreeSetO(log n)O(log n)O(log n)SortedNo null keyNo
PriorityQueuepeek O(1)O(log n)O(log n)Heap (poll sorted)NoNo
ConcurrentHashMapO(1) avgO(1)O(1)NoneNoYes
CopyOnWriteArrayListO(1) idxO(n)O(n)InsertionYesYes

HashMap: capacity power of two, load 0.75, treeify at 8 (table ≥ 64), untreeify at 6 (internals). ArrayList grows ×1.5. Immutable factories: List.of, Set.of, Map.of (no nulls, random iteration order for sets/maps).

Java language quick facts​

TopicFact
StringImmutable; literals pooled; intern(); use StringBuilder in loops
== vs equalsIdentity vs logical equality; override equals and hashCode together
Integer cacheInteger values -128..127 cached; use equals on boxed types
Pass byAlways by value (references copied)
finalVariable not reassigned / method not overridden / class not extended
Checked exceptionsMust be handled/declared; default Spring rollback ignores them
try-with-resourcesCloses in reverse order; close exceptions become suppressed
GenericsErased at runtime; PECS (? extends to read, ? super to write)
Records (16)Shallowly immutable data carriers; compact constructor for validation
Sealed (17)Closed hierarchies enabling exhaustive switch
LTS releases8, 11, 17, 21, 25
Virtual threadsJava 21; one per task, never pooled; avoid long synchronized I/O before JDK 24

Streams quick reference​

TaskCode
Filter + map + collectlist.stream().filter(p).map(f).toList()
GroupCollectors.groupingBy(f, Collectors.counting())
PartitionCollectors.partitioningBy(pred)
To map (merge fn!)Collectors.toMap(k, v, (a, b) -> a)
JoinCollectors.joining(", ")
Sum/avgmapToInt(..).sum() / Collectors.averagingDouble
FlattenflatMap(x -> x.items().stream())
Distinct sorted descdistinct().sorted(Comparator.reverseOrder())
Short-circuitanyMatch, allMatch, findFirst, limit

Streams are lazy and single-use; parallel streams share the common pool: avoid with blocking I/O (details).

Concurrency tools​

NeedUse
Visibility of a flagvolatile
Atomic counterAtomicInteger; hot counter: LongAdder
Mutual exclusionsynchronized or ReentrantLock (tryLock, conditions)
Many readers, rare writersReentrantReadWriteLock / StampedLock (optimistic read)
Thread-safe mapConcurrentHashMap + merge/compute
Producer-consumerBounded BlockingQueue
Wait for N tasksCountDownLatch (one-shot), CyclicBarrier (reusable)
Limit concurrencySemaphore
Async compositionCompletableFuture (thenCompose, allOf, orTimeout) with your own executor
I/O-bound scaleVirtual threads (newVirtualThreadPerTaskExecutor)

ThreadPoolExecutor order: core threads → queue → extra threads up to max → reject; unbounded queue ignores max (Executors). Deadlock = mutual exclusion + hold-and-wait + no preemption + circular wait; fix with lock ordering or tryLock.

JVM flags and diagnostics​

GoalFlag / tool
Heap in containers-XX:MaxRAMPercentage=75 (leave off-heap headroom)
Collector-XX:+UseG1GC (default) / -XX:+UseZGC / -XX:+UseParallelGC
GC logs-Xlog:gc*:file=gc.log:time,uptime,level,tags
Heap dump on OOM-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=...
Exit on OOM-XX:+ExitOnOutOfMemoryError
Thread dumpjcmd <pid> Thread.print
Heap dumpjcmd <pid> GC.heap_dump file.hprof
Profile in prodJFR: jcmd <pid> JFR.start duration=60s filename=rec.jfr; async-profiler flame graph
Flags in effectjcmd <pid> VM.flags

Memory areas: heap, metaspace, thread stacks, code cache, direct buffers (JVM). Exit 137 = SIGKILL/OOM-killed; 143 = SIGTERM.

Spring annotations​

AreaAnnotations
Beans@Component, @Service, @Repository, @Controller, @Configuration, @Bean, @Primary, @Qualifier, @Scope, @Lazy, @Profile, @Conditional...
Lifecycle@PostConstruct, @PreDestroy, ApplicationRunner, @EventListener, @TransactionalEventListener
Web@RestController, @RequestMapping, @GetMapping..., @PathVariable, @RequestParam, @RequestBody, @Valid, @ControllerAdvice, @ExceptionHandler, @ResponseStatus
Config@Value, @ConfigurationProperties, @PropertySource
Data@Entity, @Id, @GeneratedValue, @OneToMany(mappedBy=), @ManyToOne(fetch=LAZY), @Version, @Query, @EntityGraph, @Transactional
Cross-cutting@Aspect, @Around, @Cacheable, @CacheEvict, @Async, @Scheduled, @Retryable
Security@EnableMethodSecurity, @PreAuthorize, @PostAuthorize
Test@SpringBootTest, @WebMvcTest, @DataJpaTest, @MockitoBean, @ServiceConnection, @WithMockUser

Proxy-based features (@Transactional, @Cacheable, @Async, @PreAuthorize) skip self-invocation, private and final methods (AOP).

Bean lifecycle in one line​

Instantiate → inject → Aware → BPP before → @PostConstruct → afterPropertiesSet → init-method → BPP after (proxy) → use → @PreDestroy → destroy (lifecycle).

Spring Boot essentials​

TopicKey facts
Auto-configurationAutoConfiguration.imports + conditions; --debug shows the report
Property precedenceCLI args > system props > env vars > profile files > application files > defaults
Actuator probes/actuator/health/liveness, /actuator/health/readiness; keep dependencies out of liveness
Graceful shutdownserver.shutdown=graceful, spring.lifecycle.timeout-per-shutdown-phase
Virtual threadsspring.threads.virtual.enabled=true (Boot 3.2+)
Circular referencesProhibited by default (Boot 2.6+)
Bean overridingDisabled by default (Boot 2.1+)
Open-in-viewspring.jpa.open-in-view defaults to true; often set false

Transactions​

PropagationBehaviour
REQUIREDJoin or create (default)
REQUIRES_NEWSuspend, run independent transaction
NESTEDSavepoint
SUPPORTS / NOT_SUPPORTEDJoin if exists / suspend and run without
MANDATORY / NEVERMust have / must not have a transaction

Rollback: runtime exceptions and errors by default; checked need rollbackFor. Isolation: read committed (PostgreSQL default), repeatable read (MySQL default), serializable (retry on failure). Anomalies: dirty read, non-repeatable read, phantom, lost update, write skew (Transactions, ACID/MVCC).

JPA / Hibernate​

ProblemFix
N+1join fetch, @EntityGraph, default_batch_fetch_size, projections
LazyInitializationExceptionFetch within the transaction; use DTOs; not EAGER
join fetch + PageablePage ids first, then fetch children
Lost update@Version (optimistic), FOR UPDATE (pessimistic), atomic update
Slow bulk insertSEQUENCE ids, jdbc.batch_size, flush/clear in batches
EnumsEnumType.STRING
Entity equalsBusiness key, or id-based with proxy handling; avoid Lombok @Data

HTTP status codes​

CodeMeaningUse
200 / 201 / 202 / 204OK / Created / Accepted (async) / No contentSuccess variants
301 / 302 / 304Permanent / temporary redirect / not modifiedRedirects, caching
400Bad requestMalformed or invalid input
401UnauthenticatedMissing/invalid credentials
403ForbiddenAuthenticated but not allowed
404 / 405 / 409Not found / method not allowed / conflictResource state
412 / 422 / 429Precondition failed / unprocessable / too many requestsConcurrency control, validation, rate limits
500 / 502 / 503 / 504Server error / bad gateway / unavailable / gateway timeoutFailures

Idempotent methods: GET, PUT, DELETE, HEAD, OPTIONS; POST and PATCH are not (use idempotency keys).

SQL quick reference​

TaskPattern
Left join keep all left rowsPut right-side filters in ON, not WHERE
No matching rowsNOT EXISTS (not NOT IN with NULLs)
Top-1 per groupROW_NUMBER() OVER (PARTITION BY g ORDER BY x DESC)
RankingRANK (gaps) vs DENSE_RANK (no gaps)
UpsertINSERT ... ON CONFLICT DO UPDATE / ON DUPLICATE KEY UPDATE / MERGE
Deep pagingKeyset: WHERE id > :last ORDER BY id LIMIT n
Slow queryEXPLAIN (ANALYZE, BUFFERS); composite index equality → range → sort
Row lockingFOR UPDATE, NOWAIT, SKIP LOCKED

Normal forms: 1NF atomic values, 2NF no partial dependency, 3NF no transitive dependency (design, patterns).

Microservice patterns​

ProblemPattern
Single entry, auth, limitsAPI gateway
Find instancesService discovery (or Kubernetes Service)
Cascading failureTimeout + circuit breaker + bulkhead + bounded retry with jitter
Cross-service consistencySaga (orchestrated or choreographed)
Atomic DB change + eventTransactional outbox
Duplicate deliveryIdempotency keys / idempotent consumers
Read scaling / cross-service queriesCQRS read models
TracingTrace id propagation (W3C traceparent), OpenTelemetry
ConfigEnv vars / ConfigMap / Config Server
Strangling a monolithStrangler fig behind a gateway

Resilience4j order of aspects (outermost first): Retry → CircuitBreaker → RateLimiter → TimeLimiter → Bulkhead (Resilience4j).

Kafka settings​

GoalSettings
Durable writesacks=all, RF=3, min.insync.replicas=2, enable.idempotence=true, unclean.leader.election.enable=false
Throughputlinger.ms, batch.size, compression.type=lz4, more partitions
At-least-once consumerenable.auto.commit=false, commit after processing, idempotent handler
Avoid rebalance stormsCooperative sticky assignor, static membership, max.poll.interval.ms > processing time, smaller max.poll.records
OrderingKey by aggregate id (per-partition order only)
Poison messagesBounded retries, ErrorHandlingDeserializer, DLT (<topic>-dlt default in Spring Kafka 3)
Exactly-onceIdempotent producer + transactions + read_committed; Kafka-scoped only

Parallelism of a group ≤ partition count; lag = log end − committed offset (Kafka).

Security​

TopicRemember
401 vs 403Unauthenticated vs unauthorised
hasRole('ADMIN')Checks ROLE_ADMIN
JWTSigned not encrypted; validate signature, exp, iss, aud; short TTL + refresh rotation
FlowsAuth Code + PKCE (users), client credentials (services); avoid implicit/ROPC
CSRFKeep for cookie sessions; not needed for header-bearer APIs
Passwordsbcrypt/argon2 via DelegatingPasswordEncoder
Top flawsIDOR/broken access control, injection (use bind parameters), XSS, SSRF, mass assignment (use DTOs), vulnerable dependencies, leaked secrets

Docker and Kubernetes commands​

docker build -t app:1.0 . # build image
docker run -d --name app -p 8080:8080 -m 512m app:1.0
docker logs -f app ; docker exec -it app sh
docker stop app # SIGTERM then SIGKILL after 10 s
docker image history app:1.0 # inspect layers

kubectl get pods -n shop -o wide
kubectl describe pod <pod> # events, probe failures, OOMKilled
kubectl logs <pod> --previous # crashed container's logs
kubectl rollout status deployment/orders
kubectl rollout undo deployment/orders
kubectl top pod -n shop
kubectl debug -it <pod> --image=busybox --target=<container>
kubectl apply -f k8s/ --dry-run=server # validate against the cluster

Pod states: CrashLoopBackOff (app exits), ImagePullBackOff (registry/tag/auth), Pending (scheduling/resources), OOMKilled (memory limit).

System design numbers and checklist​

  • 1 day ≈ 86,400 s ≈ 10^5 s; average QPS = daily requests ÷ 10^5; peak 2-5×.
  • Memory ~100 ns, SSD ~100 µs, same-datacenter RTT ~0.5 ms, cross-continent ~150 ms.
  • Availability: 99.9% ≈ 8.8 h/yr downtime; 99.99% ≈ 53 min/yr.
  • Checklist: requirements → numbers → API/data → architecture → deep dives (partitioning, consistency, caching, failures) → trade-offs and evolution (framework).
  • Token bucket for bursty rate limits; consistent hashing for resharding; Base62 + id ranges for short codes; idempotency + outbox for reliable events.

Behavioural quick card​

STAR: Situation (10%), Task (10%), Action (60%, "I" + reasoning + trade-offs), Result (20%, numbers + learning). Keep 6-8 stories (details).

Next topic​

Finished this page? Track your progress (saved only in your browser).