为了账号安全,请及时绑定邮箱和手机立即绑定

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

pexels-julian-paolo-dayag-1673973

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

结尾

  如果觉得对你有帮助,可以多多评论,多多点赞哦,也可以到我的主页看看,说不定有你喜欢的文章,也可以随手点个关注哦,谢谢。

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

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消