关于后端:从trywithresources到ThreadLocal优化你的代码编写方式

31次阅读

共计 2393 个字符,预计需要花费 6 分钟才能阅读完成。

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 变量是独立的,从而防止了线程平安问题。

结尾

  如果感觉对你有帮忙,能够多多评论,多多点赞哦,也能够到我的主页看看,说不定有你喜爱的文章,也能够顺手点个关注哦,谢谢。

  我是不一样的科技宅,每天提高一点点,体验不一样的生存。咱们下期见!

正文完
 0