多线程编程注意点(持续更新)

1. 对象逸出(Escape)

    构造函数中,当前对象还没初始化完成就暴露this给外部

package com.chstudy.unsafe;

import java.util.ArrayList;
import java.util.List;

public class EventEscape {

    private final List<Event> listOfEvents;

    public EventEscape(EventSource source) {
        source.registerListener(new EventListener() {
            @Override
            public void onEvent(Event e) {
                doSomething(e);
            }
        });
        listOfEvents = new ArrayList<>();
    }

    void doSomething(Event e) {
        listOfEvents.add(e);
    }

    interface Event {

    }

    interface EventSource {
        void registerListener(EventListener listener);

    }

    interface EventListener {
        void onEvent(Event event);
    }
}    

二、并发使用的类,对成员变量的访问需要同步

package com.chstudy.unsafe;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;


@WebServlet(urlPatterns = "/count.do")
public class UnsafeCountServlet  extends GenericServlet implements Servlet {


    private Long count = 0L;

    public Long getCount() {
        return count;
    }

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        count++;
        res.getWriter().write(count+"");
        res.flushBuffer();
    }

}

三、JVM 参数,打印指定方法的汇编指令

-XX:+UnlockDiagnosticVMOptions -Xcomp -XX:+PrintAssembly -XX:CompileCommand=compileonly,*GoalNotifier.setGoal

-XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly:开启JIT反汇编
-Xcomp:让虚拟机以编译模式执行代码,使得JIT编译可以立即触发 -XX:CompileCommand=compileonly,*GoalNotifier.setGoal:只反汇编GoalNotifier的setGoal方法

四、

转载于:https://my.oschina.net/chen1988/blog/1845807

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值