### Constructor Injection Example in Spring Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/system-design/spring.md Shows how to perform dependency injection using the constructor. This is the recommended approach for mandatory dependencies. ```java @Service public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } //... } ``` -------------------------------- ### Java try-catch-finally Example Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-basis.md Demonstrates the basic structure of a try-catch-finally block in Java, showing how to catch exceptions and execute finally blocks. ```java try { System.out.println("Try to do something"); throw new RuntimeException("RuntimeException"); } catch (Exception e) { System.out.println("Catch Exception -> " + e.getMessage()); } finally { System.out.println("Finally"); } ``` -------------------------------- ### API Testing with Postman Example Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/other/test-development.md An example demonstrating how to use Postman for API functional testing. It involves setting the request method, URL, headers, and body, then executing the request and validating the response status code and body against expected results. ```text POST /api/users { "name": "John Doe", "email": "john.doe@example.com" } ``` -------------------------------- ### Execute a Redis Transaction Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md Use MULTI to start a transaction, queue commands, and EXEC to execute them. Commands are queued and executed sequentially. ```bash > MULTI OK > SET PROJECT "JavaGuide" QUEUED > GET PROJECT QUEUED > EXEC 1) OK 2) "JavaGuide" ``` -------------------------------- ### Redis Publish/Subscribe (Pub/Sub) Example Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md Illustrates the basic publish-subscribe mechanism in Redis using PUBLISH and SUBSCRIBE commands on a channel. This allows for broadcasting messages but lacks message persistence and acknowledgment. ```bash # Publisher sends a message to a channel > PUBLISH myChannel "Hello, subscribers!" (integer) 2 # Subscriber subscribes to a channel > SUBSCRIBE myChannel Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "myChannel" 3) (integer) 1 ``` -------------------------------- ### Array Example: Initialization, Modification, and Deletion Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-collection.md Demonstrates how to initialize, modify elements, and simulate deletion in a Java String array. Deletion requires manual shifting of elements. ```java // 初始化一个 String 类型的数组 String[] stringArr = new String[]{"hello", "world", "!"}; // 修改数组元素的值 stringArr[0] = "goodbye"; System.out.println(Arrays.toString(stringArr));// [goodbye, world, !] // 删除数组中的元素,需要手动移动后面的元素 for (int i = 0; i < stringArr.length - 1; i++) { stringArr[i] = stringArr[i + 1]; } stringArr[stringArr.length - 1] = null; System.out.println(Arrays.toString(stringArr));// [world, !, null] ``` -------------------------------- ### Example Java Thread Output Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-concurrent.md This is an example output from the Java code snippet that lists threads. It shows the typical threads present in a running Java application, including the main thread. ```text 5] Attach Listener //添加事件 [4] Signal Dispatcher // 分发处理给 JVM 信号的线程 [3] Finalizer //调用对象 finalize 方法的线程 [2] Reference Handler //清除 reference 线程 [1] main //main 线程,程序入口 ``` -------------------------------- ### WebSecurityEnablerConfiguration Example Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/system-design/spring.md An example of an auto-configuration class, WebSecurityEnablerConfiguration, which uses conditional annotations like @ConditionalOnBean to determine if its configuration should be applied. This specific configuration is enabled if WebSecurityConfigurerAdapter is present and other conditions are met. ```java @Configuration @ConditionalOnBean(WebSecurityConfigurerAdapter.class) @ConditionalOnMissingBean(name = BeanIds.SPRING_SECURITY_FILTER_CHAIN) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @EnableWebSecurity public class WebSecurityEnablerConfiguration { } ``` -------------------------------- ### View All MySQL Storage Engines Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/mysql.md Use the SHOW ENGINES command to list all storage engines supported by your MySQL installation. This helps identify the default engine and its capabilities. ```bash mysql> SHOW ENGINES; ``` -------------------------------- ### ArrayList Example: Initialization, Addition, Modification, and Deletion Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-collection.md Shows how to initialize, add, modify, and remove elements from a Java ArrayList. These operations are generally more convenient than with arrays. ```java // 初始化一个 String 类型的 ArrayList ArrayList stringList = new ArrayList<>(Arrays.asList("hello", "world", "!")); // 添加元素到 ArrayList 中 stringList.add("goodbye"); System.out.println(stringList);// [hello, world, !, goodbye] // 修改 ArrayList 中的元素 stringList.set(0, "hi"); System.out.println(stringList);// [hi, world, !, goodbye] // 删除 ArrayList 中的元素 stringList.remove(0); System.out.println(stringList); // [world, !, goodbye] ``` -------------------------------- ### Configuring Bean Scope with XML Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/system-design/spring.md Shows the XML configuration for setting a bean's scope, using 'singleton' as an example. This is an alternative to annotation-based configuration. ```xml ``` -------------------------------- ### Spring @Resource Examples with Multiple Implementations Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/system-design/spring.md Illustrates using @Resource for dependency injection, especially when an interface has multiple implementations. It shows how to specify the bean name using the 'name' attribute. ```java // 报错,byName 和 byType 都无法匹配到 bean @Resource private SmsService smsService; // 正确注入 SmsServiceImpl1 对象对应的 bean @Resource private SmsService smsServiceImpl1; // 正确注入 SmsServiceImpl1 对象对应的 bean(比较推荐这种方式) @Resource(name = "smsServiceImpl1") private SmsService smsService; ``` -------------------------------- ### Java String comparison example Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-basis.md Illustrates the difference between == and equals() when comparing String objects, including those created via literals and the 'new' keyword. ```java String a = new String("ab"); // a 为一个引用 String b = new String("ab"); // b为另一个引用,对象的内容一样 String aa = "ab"; // 放在常量池中 String bb = "ab"; // 从常量池中查找 System.out.println(aa == bb);// true System.out.println(a == b);// false System.out.println(a.equals(b));// true System.out.println(42 == 42.0);// true ``` -------------------------------- ### CountDownLatch Example with ExecutorService Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-concurrent.md Demonstrates using CountDownLatch to wait for multiple file processing tasks to complete before proceeding. An ExecutorService is used to manage threads for processing. ```java public class CountDownLatchExample1 { // 处理文件的数量 private static final int threadCount = 6; public static void main(String[] args) throws InterruptedException { // 创建一个具有固定线程数量的线程池对象(推荐使用构造方法创建) ExecutorService threadPool = Executors.newFixedThreadPool(10); final CountDownLatch countDownLatch = new CountDownLatch(threadCount); for (int i = 0; i < threadCount; i++) { final int threadnum = i; threadPool.execute(() -> { try { //处理文件的业务操作 //...... } catch (InterruptedException e) { e.printStackTrace(); } finally { //表示一个文件已经被完成 countDownLatch.countDown(); } }); } countDownLatch.await(); threadPool.shutdown(); System.out.println("finish"); } } ``` -------------------------------- ### Soft Reference Example Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-jvm.md Shows how to create a soft reference. Soft references are candidates for garbage collection when memory is low, making them suitable for implementing memory-sensitive caches. ```java // 软引用 String str = new String("abc"); SoftReference softReference = new SoftReference(str); ``` -------------------------------- ### Thread Creation for ParityPrinter (synchronized+wait/notify) Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/real-interview-experience/dachang/2025-alibaba-taotian-1.md Demonstrates how to create and start two threads, one for printing odd numbers and another for even numbers, using the `ParityPrinter` class. ```java // 打印 1-100 ParityPrinter printer = new ParityPrinter(100); // 创建打印奇数和偶数的线程 Thread t1 = new Thread(printer::printOdd, "Odd"); Thread t2 = new Thread(printer::printEven, "Even"); t1.start(); t2.start(); ``` -------------------------------- ### Spring @Autowired Examples with Multiple Implementations Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/system-design/spring.md Demonstrates how to handle multiple implementations of an interface when using @Autowired. It shows incorrect usage and correct usage with property naming or @Qualifier. ```java // SmsService 接口有两个实现类:SmsServiceImpl1、SmsServiceImpl2(均被 Spring 管理) // 报错:byType 匹配到多个 Bean,且属性名 "smsService" 与两个实现类的默认名称(smsServiceImpl1、smsServiceImpl2)都不匹配 @Autowired private SmsService smsService; // 正确:属性名 "smsServiceImpl1" 与实现类 SmsServiceImpl1 的默认名称匹配 @Autowired private SmsService smsServiceImpl1; // 正确:通过 @Qualifier 显式指定 Bean 名称 "smsServiceImpl1" @Autowired @Qualifier(value = "smsServiceImpl1") private SmsService smsService; ``` -------------------------------- ### Java Autoboxing and Unboxing Example Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-basis.md Demonstrates autoboxing (converting primitive to wrapper type) and unboxing (converting wrapper type to primitive). Autoboxing uses Integer.valueOf() and unboxing uses intValue(). ```java Integer i = 10; //装箱 int n = i; //拆箱 ``` -------------------------------- ### Custom ThreadFactory for Naming Threads Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-concurrent.md Implement the `ThreadFactory` interface to create custom thread factories. This example demonstrates setting a specific name prefix for threads, which aids in debugging and problem localization. ```java import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; /** * 线程工厂,它设置线程名称,有利于我们定位问题。 */ public final class NamingThreadFactory implements ThreadFactory { private final AtomicInteger threadNum = new AtomicInteger(); private final String name; /** * 创建一个带名字的线程池生产工厂 */ public NamingThreadFactory(String name) { this.name = name; } @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName(name + " [#" + threadNum.incrementAndGet() + "]"); return t; } } ``` -------------------------------- ### Weak Reference Example Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-jvm.md Demonstrates creating a weak reference. Objects with only weak references are collected by the garbage collector regardless of memory availability, offering a shorter lifecycle than soft references. ```java String str = new String("abc"); WeakReference> weakReference = new WeakReference<>(str); str = null; //str变成软引用,可以被收集 ``` -------------------------------- ### Example of CallerRunsPolicy Blocking Main Thread Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-concurrent.md Demonstrates how CallerRunsPolicy can cause the main thread to block when handling a rejected task, especially if the task is time-consuming. This setup uses a small thread pool with a limited queue size. ```java public class ThreadPoolTest { private static final Logger log = LoggerFactory.getLogger(ThreadPoolTest.class); public static void main(String[] args) { // 创建一个线程池,核心线程数为1,最大线程数为2 // 当线程数大于核心线程数时,多余的空闲线程存活的最长时间为60秒, // 任务队列为容量为1的ArrayBlockingQueue,饱和策略为CallerRunsPolicy。 ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 2, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1), new ThreadPoolExecutor.CallerRunsPolicy()); // 提交第一个任务,由核心线程执行 threadPoolExecutor.execute(() -> { log.info("核心线程执行第一个任务"); ThreadUtil.sleep(1, TimeUnit.MINUTES); }); // 提交第二个任务,由于核心线程被占用,任务将进入队列等待 threadPoolExecutor.execute(() -> { log.info("非核心线程处理入队的第二个任务"); ThreadUtil.sleep(1, TimeUnit.MINUTES); }); // 提交第三个任务,由于核心线程被占用且队列已满,创建非核心线程处理 threadPoolExecutor.execute(() -> { log.info("非核心线程处理第三个任务"); ThreadUtil.sleep(1, TimeUnit.MINUTES); }); // 提交第四个任务,由于核心线程和非核心线程都被占用,队列也满了,根据CallerRunsPolicy策略,任务将由提交任务的线程(即主线程)来执行 threadPoolExecutor.execute(() -> { log.info("主线程处理第四个任务"); ThreadUtil.sleep(2, TimeUnit.MINUTES); }); // 提交第五个任务,主线程被第四个任务卡住,该任务必须等到主线程执行完才能提交 threadPoolExecutor.execute(() -> { log.info("核心线程执行第五个任务"); }); // 关闭线程池 threadPoolExecutor.shutdown(); } } ``` -------------------------------- ### Java Object Creation Process Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-jvm.md Outlines the five steps JVM (HotSpot) takes to create an object: class loading check, memory allocation (using pointer collision or free list), zero-initialization, object header setup, and finally, execution of the init method. ```java // Step 1: Class loading check // Step 2: Memory allocation (Pointer Collision or Free List, CAS + retry or TLAB for thread safety) // Step 3: Zero-initialization // Step 4: Object header setup (metadata, hash code, GC age, lock status) // Step 5: Execute init method () ``` -------------------------------- ### Get Current Memory Eviction Policy Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md Use `config get maxmemory-policy` to retrieve the currently active memory eviction strategy in Redis. ```bash > config get maxmemory-policy maxmemory-policy noeviction ``` -------------------------------- ### E-commerce Promotions with Strategy Pattern Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/system-design/design-pattern.md Demonstrates using the Strategy pattern for different promotional offers in an e-commerce system. New promotion types can be added without modifying existing order logic. ```java PromotionStrategy june18Strategy = new CashRebateStrategy(300, 50); Order order618 = new Order(june18Strategy); double price618 = order618.getFinalPrice(400); // 结果:350 PromotionStrategy anniversaryStrategy = new DiscountStrategy(0.9); Order anniversaryOrder = new Order(anniversaryStrategy); double priceAnniversary = anniversaryOrder.getFinalPrice(400); // 结果:360 Order normalOrder = new Order(new NoPromotionStrategy()); ``` -------------------------------- ### Get Max Memory Configuration Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md Use `config get maxmemory` to check the current maximum memory limit set for Redis. A value of 0 indicates no limit. ```bash > config get maxmemory maxmemory 0 ``` -------------------------------- ### MySQL EXPLAIN 命令示例 Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/mysql.md 使用 EXPLAIN 命令分析 SQL 查询的执行计划,了解查询的执行方式、索引使用情况等。适用于 SELECT, DELETE, INSERT, REPLACE, 和 UPDATE 语句。 ```sql mysql> EXPLAIN SELECT `score`,`name` FROM `cus_order` ORDER BY `score` DESC; +----+-------------+-----------+------------+------+---------------+------+---------+------+--------+----------+----------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+-----------+------------+------+---------------+------+---------+------+--------+----------+----------------+ | 1 | SIMPLE | cus_order | NULL | ALL | NULL | NULL | NULL | NULL | 997572 | 100.00 | Using filesort | +----+-------------+-----------+------------+------+---------------+------+---------+------+--------+----------+----------------+ 1 row in set, 1 warning (0.00 sec) ``` -------------------------------- ### Stateless Bean Example: UserService Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/system-design/spring.md This Java code defines a stateless UserService component. It serves as an example of a typical Spring bean that is thread-safe because it does not maintain any mutable state. ```java import org.springframework.stereotype.Component; // 定义了一个用户服务,它仅包含业务逻辑而不保存任何状态。 @Component public class UserService { public User findUserById(Long id) { //... } //... } ``` -------------------------------- ### Prestarting Core Threads in ThreadPoolExecutor Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-concurrent.md Utilize `prestartCoreThread()` to start a single core thread before submitting tasks, or `prestartAllCoreThreads()` to start all core threads. This can be used for thread pool preheating. ```java threadPool.prestartCoreThread(); ``` ```java threadPool.prestartAllCoreThreads(); ``` -------------------------------- ### Simple Redis List as a Message Queue Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md Demonstrates using Redis List commands RPUSH and LPOP for a basic producer-consumer pattern. This method is simple but can be inefficient due to polling. ```bash # Producer sends messages > RPUSH myList msg1 msg2 (integer) 2 > RPUSH myList msg3 (integer) 3 # Consumer consumes messages > LPOP myList "msg1" ``` -------------------------------- ### Payment Processing with Strategy Pattern Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/system-design/design-pattern.md Illustrates the Strategy pattern for handling various payment methods. New payment options can be integrated by adding new strategy implementations without altering the payment service. ```java public class PaymentService { private PaymentStrategy paymentStrategy; // 动态设置支付策略(如用户选择微信支付时传入WeChatPayStrategy) public void setPaymentStrategy(PaymentStrategy strategy) { this.paymentStrategy = strategy; } public PaymentResult processPayment(double amount) { return paymentStrategy.pay(amount); } } ``` -------------------------------- ### String Constant Pool Example Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-jvm.md This example demonstrates how string literals are interned in the String Constant Pool. When 'aa' and 'bb' are both assigned the literal 'ab', they point to the same object in the pool, resulting in 'true' when compared with '=='. ```java // 在字符串常量池中创建字符串对象 ”ab“ // 将字符串对象 ”ab“ 的引用赋值给给 aa String aa = "ab"; // 直接返回字符串常量池中字符串对象 ”ab“,赋值给引用 bb String bb = "ab"; System.out.println(aa==bb); // true ``` -------------------------------- ### Get the Number of Slow Query Log Entries Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md Check the current number of entries stored in the Redis slow query log. ```bash 127.0.0.1:6379> SLOWLOG LEN (integer) 128 ``` -------------------------------- ### Positive and Negative Test Cases for Login Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/other/test-development.md Examples illustrating positive and negative testing for a login function. Positive testing uses valid credentials for successful login, while negative testing includes invalid inputs like empty fields, incorrect passwords, and malicious inputs to test system robustness. ```text Positive Test: Correct username + Correct password → Login Success Negative Test: Username empty / Password empty, Incorrect password, Input excessively long string, Script injection, Multiple incorrect attempts triggering lock/captcha ``` -------------------------------- ### Initialize Bitmap for Active Users Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md Use SETBIT to mark a user as active on a specific date. The date serves as the key, and the user ID as the offset. A value of 1 indicates activity. ```bash > SETBIT 20210308 1 1 (integer) 0 > SETBIT 20210308 2 1 (integer) 0 > SETBIT 20210309 1 1 (integer) 0 ``` -------------------------------- ### ClassLoader Parent Field Example Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-jvm.md Demonstrates the composition relationship in ClassLoader, where a parent ClassLoader is held as a field, favoring composition over inheritance. ```java public abstract class ClassLoader { ... // 组合 private final ClassLoader parent; protected ClassLoader(ClassLoader parent) { this(checkCreateClassLoader(), parent); } ... } ``` -------------------------------- ### Object Circular Reference Example Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-jvm.md Demonstrates how reference counting can fail to detect cycles where objects mutually reference each other, leading to memory leaks. ```java public class ReferenceCountingGc { Object instance = null; public static void main(String[] args) { ReferenceCountingGc objA = new ReferenceCountingGc(); ReferenceCountingGc objB = new ReferenceCountingGc(); objA.instance = objB; objB.instance = objA; objA = null; objB = null; } } ``` -------------------------------- ### Spring Bean XML配置 init-method Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/system-design/spring.md 展示了如何在Spring XML配置文件中为Bean指定自定义的初始化方法`init()`。 ```xml ``` -------------------------------- ### HyperLogLog: Get UV Count Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md Use PFCOUNT to retrieve the approximate count of unique elements (e.g., users) stored in one or more HyperLogLog structures. ```redis PFCOUNT PAGE_1:UV ``` -------------------------------- ### Configuring LFU Maxmemory Policy in Redis Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md Example configurations for setting the LFU (Least Frequently Used) maxmemory policy in the Redis configuration file. ```properties # 使用 volatile-lfu 策略 maxmemory-policy volatile-lfu # 或者使用 allkeys-lfu 策略 maxmemory-policy allkeys-lfu ``` -------------------------------- ### Configure Eden and Survivor Ratios Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-jvm.md Set the ratio between the Eden space and Survivor spaces within the young generation using `-XX:SurvivorRatio`. A larger value means smaller Survivor spaces. ```bash -XX:SurvivorRatio=8 ``` -------------------------------- ### Using Redis --hotkeys Parameter Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md This command scans the entire keyspace to find hot keys and their access frequencies. It requires a LFU maxmemory-policy to be set. ```bash # redis-cli -p 6379 --hotkeys # Scanning the entire keyspace to find hot keys as well as # average sizes per key type. You can use -i 0.1 to sleep 0.1 sec # per 100 SCAN commands (not usually needed). Error: ERR An LFU maxmemory policy is not selected, access frequency not tracked. Please note that when switching between policies at runtime LRU and LFU data will take some time to adjust. ``` -------------------------------- ### Abstract Factory Pattern Implementation in Java Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/system-design/design-pattern.md This Java code demonstrates the Abstract Factory pattern. It includes abstract products (Device, Accessory), concrete products (SmartPhone, Laptop, PhoneCase, LaptopBag), an abstract factory (DeviceSetFactory), concrete factories (PhoneSetFactory, LaptopSetFactory), and a client demonstrating its usage. ```java package facytoy; // 抽象产品A:设备 interface Device { void operate(); // 操作设备 } // 抽象产品B:配件 interface Accessory { void use(); // 使用配件 } // 具体产品A1:智能手机 class SmartPhone implements Device { @Override public void operate() { System.out.println("智能手机:开机使用"); } } // 具体产品A2:笔记本电脑 class Laptop implements Device { @Override public void operate() { System.out.println("笔记本电脑:开机使用"); } } // 具体产品B1:手机壳 class PhoneCase implements Accessory { @Override public void use() { System.out.println("手机壳:保护手机\n"); } } // 具体产品B2:电脑包 class LaptopBag implements Accessory { @Override public void use() { System.out.println("电脑包:携带电脑\n"); } } // 抽象工厂:设备套装工厂 interface DeviceSetFactory { Device createDevice(); Accessory createAccessory(); } // 具体工厂:手机套装工厂 class PhoneSetFactory implements DeviceSetFactory { @Override public Device createDevice() { return new SmartPhone(); } @Override public Accessory createAccessory() { return new PhoneCase(); } } // 具体工厂:电脑套装工厂 class LaptopSetFactory implements DeviceSetFactory { @Override public Device createDevice() { return new Laptop(); } @Override public Accessory createAccessory() { return new LaptopBag(); } } // 客户端使用 public class SimplifiedAbstractFactoryDemo { public static void main(String[] args) { // 创建手机套装 System.out.println("=== 手机套装 ==="); DeviceSetFactory phoneFactory = new PhoneSetFactory(); phoneFactory.createDevice().operate(); phoneFactory.createAccessory().use(); // 创建电脑套装 System.out.println("=== 电脑套装 ==="); DeviceSetFactory laptopFactory = new LaptopSetFactory(); laptopFactory.createDevice().operate(); laptopFactory.createAccessory().use(); } } ``` -------------------------------- ### Semaphore acquire and release Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-concurrent.md Demonstrates the basic usage of Semaphore to control access to a limited number of resources. acquire() decrements the permit count (blocking if none are available), and release() increments it. ```java // 初始共享资源数量 final Semaphore semaphore = new Semaphore(5); // 获取1个许可 semaphore.acquire(); // 释放1个许可 semaphore.release(); ``` -------------------------------- ### ArrayList Adding Null Values Example Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/java/java-collection.md Demonstrates that ArrayLists can store null values. However, it is generally discouraged due to potential NullPointerException issues. ```java ArrayList listOfStrings = new ArrayList<>(); listOfStrings.add(null); listOfStrings.add("java"); System.out.println(listOfStrings); ``` -------------------------------- ### Simple Factory Pattern Implementation Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/system-design/design-pattern.md This snippet demonstrates the Simple Factory pattern where a single factory object creates instances of different devices based on a type string. It decouples the client from concrete product implementations. ```Java interface Device { void operate(); // 操作设备 } class Phone implements Device { @Override public void operate() { System.out.println("手机操作:开机 -> 显示主界面 -> 关机\n"); } } class Computer implements Device { @Override public void operate() { System.out.println("电脑操作:开机 -> 加载系统 -> 关机\n"); } } class DeviceFactory { public static Device createDevice(String type) { if (type.equalsIgnoreCase("PHONE")) { return new Phone(); } else if (type.equalsIgnoreCase("COMPUTER")) { return new Computer(); } return null; } } public class SimpleFactoryDemo { public static void main(String[] args) { Device phone = DeviceFactory.createDevice("PHONE"); Device computer = DeviceFactory.createDevice("COMPUTER"); phone.operate(); computer.operate(); } } ``` -------------------------------- ### Clear the Slow Query Log Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md Reset the Redis slow query log, removing all stored entries. This is useful for freeing up memory or starting a fresh analysis. ```bash 127.0.0.1:6379> SLOWLOG RESET OK ``` -------------------------------- ### Check Set Size with SCARD Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md Use the `SCARD` command to get the number of elements in a set stored at a key. This aids in identifying large set big keys. ```redis SCARD ``` -------------------------------- ### Check List Length with LLEN Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md Use the `LLEN` command to get the number of elements in a list stored at a key. This is helpful for detecting large list big keys. ```redis LLEN ``` -------------------------------- ### Redis Transaction with WATCH (External Modification - Different Scenario) Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/database/redis.md This example shows another scenario where an external modification to a WATCHed key before MULTI prevents transaction execution. ```bash > SET PROJECT "JavaGuide" OK > WATCH PROJECT OK > SET PROJECT "JavaGuide2" OK > MULTI OK > GET USER QUEUED > EXEC (nil) ``` -------------------------------- ### InitializingBean接口定义 Source: https://github.com/snailclimb/javaguide-interview/blob/master/docs/system-design/spring.md 定义了Spring Bean初始化扩展点`InitializingBean`接口,要求实现`afterPropertiesSet`方法来执行Bean的初始化逻辑。 ```java public interface InitializingBean { // 初始化逻辑 void afterPropertiesSet() throws Exception; } ```