相关疑难解决方法(0)

jvm重新排序/能见度效应测试

在编写一些java文章时,我试图在多线程环境中的非同步对象构造的情况下重现重新排序.构建重型对象时没有同步/挥发性/韵母和其他线程在构造函数调用后立即访问它的情况.这是我尝试的代码:

public class ReorderingTest {
    static SomeObject<JPanel>[] sharedArray = new SomeObject[100];

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            String name = "watcher" + i;
            new Thread(new Watcher(name)).start();
            System.out.printf("watcher %s started!%n", name);
        }
    }

    static class Watcher implements Runnable {
        private String name;

        Watcher(String name) {
            this.name = name;
        }

        public void run() {
            while (true) {
                int randomIndex = (int) (Math.random() * sharedArray.length);
                SomeObject<JPanel> item = sharedArray[randomIndex];
                if (item …
Run Code Online (Sandbox Code Playgroud)

java concurrency multithreading memory-visibility

5
推荐指数
1
解决办法
664
查看次数

尽管没有代码明确泄漏,未初始化的对象泄露给另一个线程?

让我们看看这个简单的Java程序:

import java.util.*;

class A {
    static B b;
    static class B {
        int x;
        B(int x) {
            this.x = x;
        }
    }
    public static void main(String[] args) {
        new Thread() {
            void f(B q) {
                int x = q.x;
                if (x != 1) {
                    System.out.println(x);
                    System.exit(1);
                }
            }
            @Override
            public void run() {
                while (b == null);
                while (true) f(b);
            }
        }.start();
        for (int x = 0;;x++)
            b = new B(Math.max(x%2,1));
    }
}
Run Code Online (Sandbox Code Playgroud)

主线程

主线程创建的实例Bx设置为1,则该实例写入静态字段 …

java concurrency initialization memory-visibility

4
推荐指数
1
解决办法
945
查看次数