从try-with-resources到ThreadLocal,优化你的代码编写方式!

1. 运用try-with-resources简化文件读取操作:

修正前:

FileInputStream fis = null;
try {
    fis = new FileInputStream("file.txt");
    // ...
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        try {
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

修正后:

try (FileInputStream fis = new FileInputStream("file.txt")) {
    // ...
} catch (IOException e) {
    e.printStackTrace();
}

2. 运用Lambda表达式简化集合操作:

修正前:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
for (String name : names) {
    System.out.println(name);
}

修正后:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));

3. 运用StringBuilder类拼接字符串:

修正前:

String s = "";
for (int i = 0; i < 10; i++) {
    s += i;
}

修正后:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
    sb.append(i);
}
String s = sb.toString();

4. 运用静态导入简化代码:

修正前:

System.out.println(Math.sqrt(2));

修正后:

import static java.lang.Math.sqrt;
System.out.println(sqrt(2));

5. 运用断语简化调试:

修正前:

if (x < 0) {
    throw new IllegalArgumentException("x must be non-negative");
}

修正后:

assert x >= 0 : "x must be non-negative";

6. 运用Optional类处理可能为空的目标:

修正前:

String s = null;
if (s != null) {
    System.out.println(s.length());
}

修正后:

Optional<String> optional = Optional.ofNullable(null);
optional.ifPresent(s -> System.out.println(s.length()));

7. 运用枚举类代替常量:

修正前:

public static final int STATUS_NEW = 0;
public static final int STATUS_PROCESSING = 1;
public static final int STATUS_COMPLETED = 2;

修正后:

public enum Status {
    NEW,
    PROCESSING,
    COMPLETED
}

8. 运用自定义反常类代替通用反常类:

修正前:

try {
    // ...
} catch (Exception e) {
    e.printStackTrace();
}

修正后:

try {
    // ...
} catch (MyCustomException e) {
    e.printStackTrace();
}

9. 运用Lambda表达式和Stream API简化集合操作:

修正前:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = new ArrayList<>();
for (int number : numbers) {
    if (number % 2 == 0) {
        evenNumbers.add(number);
    }
}

修正后:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()

10. 运用ThreadLocal避免线程安全问题:

修正前:

public class MyRunnable implements Runnable {
    private int count = 0;
    public void run() {
        for (int i = 0; i < 100000; i++) {
            count++;
        }
        System.out.println(count);
    }
}

修正后:

public class MyRunnable implements Runnable {
    private ThreadLocal<Integer> count = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };
    public void run() {
        for (int i = 0; i < 100000; i++) {
            count.set(count.get() + 1);
        }
        System.out.println(count.get());
    }
}

  在多线程环境下,运用普通的成员变量会导致线程安全问题,而运用ThreadLocal能够保证每个线程拜访的变量是独立的,避免了线程安全问题。在上面的示例中,运用ThreadLocal保证了每个线程拜访的count变量是独立的,然后避免了线程安全问题。

结束

  如果觉得对你有帮助,能够多多评论,多多点赞哦,也能够到我的主页看看,说不定有你喜欢的文章,也能够顺手点个重视哦,谢谢。

  我是不一样的科技宅,每天前进一点点,体验不一样的生活。咱们下期见!