This module provides a comprehensive review of all concepts covered in this sprint, preparing you for the sprint challenge. We'll revisit key topics and ensure you have a solid understanding of the material.
This video provides a comprehensive review of all key concepts covered throughout the sprint, preparing you for the sprint challenge and future units.
// Creating a thread using Runnable
public class TaskExecutor {
public static void main(String[] args) {
// Create multiple threads for concurrent execution
Thread downloadThread = new Thread(new DownloadTask(), "DownloadThread");
Thread processingThread = new Thread(new ProcessingTask(), "ProcessingThread");
// Start threads
downloadThread.start();
processingThread.start();
// Join threads to wait for completion
try {
downloadThread.join();
processingThread.join();
} catch (InterruptedException e) {
System.err.println("Thread interrupted: " + e.getMessage());
}
System.out.println("All tasks completed");
}
}
class DownloadTask implements Runnable {
@Override
public void run() {
// Thread-safe code with proper synchronization
synchronized(this) {
System.out.println("Downloading data in " + Thread.currentThread().getName());
// Simulate work
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
// Publishing metrics to CloudWatch
private void publishMetrics(String metricName, double value) {
try {
// Create CloudWatch client
AmazonCloudWatch cloudWatch = AmazonCloudWatchClientBuilder.standard()
.withRegion(Regions.US_EAST_1)
.build();
// Define metric with dimensions
MetricDatum datum = new MetricDatum()
.withMetricName(metricName)
.withUnit(StandardUnit.Count)
.withValue(value)
.withDimensions(
new Dimension()
.withName("ServiceName")
.withValue("UserService"),
new Dimension()
.withName("Environment")
.withValue("Production")
);
// Create and submit request
PutMetricDataRequest request = new PutMetricDataRequest()
.withNamespace("MyApplication")
.withMetricData(datum);
cloudWatch.putMetricData(request);
logger.info("Published metric: " + metricName + " with value: " + value);
} catch (Exception e) {
logger.error("Failed to publish CloudWatch metric", e);
}
}
// Processing data with Stream API and lambda expressions
public class DataProcessor {
public List<UserDTO> processUsers(List<User> users) {
return users.stream()
// Filter active users using Predicate
.filter(user -> user.isActive() && user.getLastLogin().isAfter(LocalDate.now().minusDays(30)))
// Transform User to UserDTO using Function
.map(user -> {
UserDTO dto = new UserDTO();
dto.setId(user.getId());
dto.setDisplayName(user.getFirstName() + " " + user.getLastName());
dto.setLastLoginDays(ChronoUnit.DAYS.between(user.getLastLogin(), LocalDate.now()));
return dto;
})
// Sort by last login using Comparator and method reference
.sorted(Comparator.comparing(UserDTO::getLastLoginDays))
// Limit to top 10 most recent
.limit(10)
// Collect results
.collect(Collectors.toList());
}
// Using various functional interfaces
public void demonstrateFunctionalInterfaces() {
// Supplier - provides a value
Supplier<LocalDate> dateSupplier = LocalDate::now;
// Consumer - accepts a value
Consumer<String> logger = message -> System.out.println("[LOG]: " + message);
// Function - transforms input to output
Function<String, Integer> wordCounter = s -> s.split("\\s+").length;
// Predicate - tests a condition
Predicate<Integer> isEven = num -> num % 2 == 0;
}
}
To prepare for the sprint challenge, review the following: