synchronized字符串常量

前言

synchronized 锁字符串常量语法上可行,但是不推荐

synchronized字符串常量

csharp 复制代码
public class StringSyncDemo {

    static void main() throws InterruptedException {
        String str = "aa";
        Thread thread1 = Thread.startVirtualThread(() -> {
            hello(str);
        });
        Thread thread2 = Thread.startVirtualThread(() -> {
            hello("aa");
        });
        thread1.join();
        thread2.join();
    }

    public static void hello(String str) {
        synchronized (str) {
            System.out.println(Thread.currentThread() + ":进入锁===============" + str);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread() + ":结束锁===============" + str);

        }
    }
}

输出

java 复制代码
package cn.com.ut.sept.sync;

public class StringSyncDemo {

    static void main() throws InterruptedException {
        String str = "aa";
        Thread thread1 = Thread.startVirtualThread(() -> {
            hello(str);
        });
        Thread thread2 = Thread.startVirtualThread(() -> {
            hello("bb");
        });
        thread1.join();
        thread2.join();
    }

    public static void hello(String str) {
        synchronized (str) {
            System.out.println(Thread.currentThread() + ":进入锁===============" + str);
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread() + ":结束锁===============" + str);

        }
    }
}

输出

总结

同一个字符串常量都会锁同一个对象。不同模块、第三方库、框架内部如果恰好也用了同一个字符串常量,就可能产生意外竞争,甚至死锁

相关推荐
qq_4523962316 小时前
第三篇:Transactional Outbox 模式详解
java·kubernetes·rocketmq
30955666617 小时前
股票接口重试怎么分类:正常、空数组与错误响应的幂等处理
java·大数据·开发语言·数据库·php·api接口·股票数据api接口
努力的小雨19 小时前
手里捏着纸,谁来暂停视频?我把折纸老师塞进了 AI 眼镜
后端
狗头大军之江苏分军20 小时前
《潮水漫过十七岁》倒计时
前端·javascript·后端
Wellijohn20 小时前
dict、tuple、dataclass 还是 slots?我把 6 种数据载体的 8 项开销全测了一遍
后端·python·性能优化
HarmonSir21 小时前
OpenManus 的架构解析:另一个通用 Agent 的最小内核与扩展边界
后端·架构
hsfxuebao21 小时前
Sandbox(沙箱)到底是什么?
后端
一条Go21 小时前
proto 契约:校验注解、错误码与「文案即接口」
后端·github