Advanced Java topics delve into more complex areas such as concurrency, design patterns, and Java frameworks. Understanding these topics can set you apart from other candidates and demonstrate your depth of knowledge in Java.
For a deeper dive into advanced topics, check out our article: Advanced Java Topics.
Multithreading is a Java feature that allows concurrent execution of two or more threads, enabling better resource utilization.
You can create a thread by extending the Thread
class or implementing the Runnable
interface.
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
MyThread thread = new MyThread();
thread.start();
Runnable
and Thread
?Runnable
is an interface that represents a task, while Thread
is a class that represents a thread of execution.
Synchronization is a mechanism that ensures that only one thread can access a resource at a time, preventing data inconsistency.
You can synchronize a method by using the synchronized
keyword in its declaration.
public synchronized void myMethod() {
// synchronized code
}
A deadlock occurs when two or more threads are blocked forever, each waiting for the other to release a resource.
You can prevent deadlock by ensuring that all threads acquire locks in a consistent order.
volatile
keyword in Java?The volatile
keyword indicates that a variable's value will be modified by different threads, ensuring visibility of changes across threads.
private volatile int counter;
Executor
framework in Java?The Executor
framework provides a higher-level replacement for managing threads, allowing you to decouple task submission from the mechanics of how each task will be run.
ExecutorService
?You can create a thread pool using the Executors.newFixedThreadPool()
method.
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
// task code
});
Future
interface in Java?The Future
interface represents the result of an asynchronous computation, allowing you to retrieve the result once it is available.
Callable
interface?The Callable
interface is similar to Runnable
, but it can return a result and throw a checked exception.
Callable<String> task = () -> {
return "Result";
};
CountDownLatch
class?The CountDownLatch
class is a synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
CountDownLatch latch = new CountDownLatch(3);
latch.countDown(); // Decrease count
CyclicBarrier
class?The CyclicBarrier
class allows a set of threads to all wait for each other to reach a common barrier point.
CyclicBarrier barrier = new CyclicBarrier(3);
barrier.await(); // Wait for others
Semaphore
class?The Semaphore
class is a counting semaphore that can be used to control access to a resource by multiple threads.
Semaphore semaphore = new Semaphore(1);
semaphore.acquire(); // Acquire a permit
ForkJoinPool
class?The ForkJoinPool
class is designed for parallel processing of tasks that can be broken down into smaller subtasks.
CompletableFuture
class?The CompletableFuture
class represents a future result of an asynchronous computation, allowing you to build complex asynchronous pipelines.
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "Result";
});
Stream API
in Java?The Stream API allows you to process sequences of elements (like collections) in a functional style.
You can create a stream from a collection using the stream()
method.
List<String> list = Arrays.asList("A", "B", "C");
Stream<String> stream = list.stream();
filter()
method in streams?The filter()
method is used to filter elements based on a predicate.
List<String> filtered = list.stream()
.filter(s -> s.startsWith("A"))
.collect(Collectors.toList());
map()
method in streams?The map()
method is used to transform each element in the stream.
List<Integer> lengths = list.stream()
.map(String::length)
.collect(Collectors.toList());
reduce()
method in streams?The reduce()
method is used to combine elements in the stream into a single result.
Optional<String> concatenated = list.stream()
.reduce((s1, s2) -> s1 + s2);
Collectors
class?The Collectors
class provides various static methods for collecting the elements of a stream into collections.
You can collect elements into a list using the Collectors.toList()
method.
List<String> collected = list.stream()
.collect(Collectors.toList());
Optional
class?The Optional
class is a container object which may or may not contain a non-null value, used to avoid null references.
Optional<String> optional = Optional.of("Hello");
Optional
object?You can create an Optional
object using the Optional.of()
, Optional.ofNullable()
, or Optional.empty()
methods.
Optional<String> optional = Optional.ofNullable("Hello");
Optional
has a value?You can check if an Optional
has a value using the isPresent()
method.
if (optional.isPresent()) {
System.out.println(optional.get());
}
StreamBuilder
class?The StreamBuilder
class is used to create a stream from a sequence of elements.
Stream<String> stream = Stream.of("A", "B", "C");
CompletableFuture
class?The CompletableFuture
class represents a future result of an asynchronous computation, allowing you to build complex asynchronous pipelines.
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
return "Result";
});
ForkJoinPool
class?The ForkJoinPool
class is designed for parallel processing of tasks that can be broken down into smaller subtasks.
Java Memory Model
?The Java Memory Model defines how threads interact through memory and what behaviors are allowed in concurrent programming.
Garbage collection is an automatic memory management process that reclaims memory by removing objects that are no longer in use.
Java provides several garbage collectors, including Serial GC, Parallel GC, CMS (Concurrent Mark-Sweep) GC, and G1 (Garbage-First) GC.
Java Native Interface (JNI)
?The Java Native Interface (JNI) is a framework that allows Java code to call or be called by native applications and libraries written in other languages like C or C++.
Reflection is a feature that allows inspection and manipulation of classes, methods, and fields at runtime.
You can access a class's methods using the getDeclaredMethods()
method of the Class
class.
Method[] methods = MyClass.class.getDeclaredMethods();
Java Stream API
?The Java Stream API allows you to process sequences of elements (like collections) in a functional style.
Optional
class used for?The Optional
class is used to represent a value that may or may not be present, helping to avoid null references.
try-with-resources
statement?The try-with-resources
statement is used to automatically close resources when they are no longer needed.
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
// read file
}
Java 8 Date and Time API
?The Java 8 Date and Time API provides a comprehensive and standardized way to handle date and time in Java.
You can create a date using the LocalDate
class.
LocalDate date = LocalDate.now();
Stream.of()
method?The Stream.of()
method creates a stream from a sequence of elements.
Stream<String> stream = Stream.of("A", "B", "C");
Collectors.toMap()
method?The Collectors.toMap()
method collects elements into a map.
Map<String, Integer> map = list.stream()
.collect(Collectors.toMap(String::toString, String::length));
CompletableFuture
class used for?The CompletableFuture
class is used for asynchronous programming, allowing you to write non-blocking code.
ForkJoinPool
class used for?The ForkJoinPool
class is used for parallel processing of tasks that can be broken down into smaller subtasks.
Java Module System
introduced in Java 9?The Java Module System allows you to modularize your Java applications, improving encapsulation and dependency management.
var
keyword in Java 10?The var
keyword allows for local variable type inference, enabling you to declare variables without specifying their type explicitly.
var list = new ArrayList<String>(); // Type inferred as ArrayList
switch
expression introduced in Java 12?The switch
expression allows you to use the switch
statement as an expression, returning a value.
var result = switch (day) {
case MONDAY -> "Start of the week";
case FRIDAY -> "End of the week";
default -> "Midweek";
};
Text Blocks
feature introduced in Java 13?Text Blocks allow you to create multi-line string literals in a more readable way.
String text = """
This is a text block
that spans multiple lines.
""";
Pattern Matching for instanceof
feature introduced in Java 14?Pattern Matching for instanceof simplifies the common practice of checking if an object is an instance of a specific class and then casting it.
if (obj instanceof String str) {
System.out.println(str.length());
}