我们知道,ReentrantLock有一个最大的重入限制:Integer.MAX_VALUE; synchronized块是否也有重入限制?
更新:我发现很难为同步重入编写测试代码:
public class SyncReentry {
public static void main(String[] args) {
synchronized (SyncReentry.class) {
synchronized (SyncReentry.class) {
// ...write synchronized block for ever
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮助编写一些同步重入限制测试的代码吗?
根据ConcurrentHashMap中的java文档:
* Ideally, the frequency of nodes in bins follows a Poisson distribution
* (http://en.wikipedia.org/wiki/Poisson_distribution) with a
* parameter of about 0.5 on average, given the resizing threshold
* of 0.75, although with a large variance because of resizing
* granularity. Ignoring variance, the expected occurrences of
* list size k are (exp(-0.5) * pow(0.5, k) / factorial(k)). The
* first values are:
Run Code Online (Sandbox Code Playgroud)
问题是:0.5这个参数是怎么来的?
来自Java Concurrency In Practice一书:
要安全地发布对象,必须同时使对对象的引用和对象的状态对其他线程可见。正确构造的对象可以通过以下方式安全地发布:
- 从静态初始化器初始化对象引用;
- 将对其的引用存储到 volatile 字段或 AtomicReference 中;
- 将对其的引用存储到正确构造的对象的最终字段中;或者
- 将对其的引用存储到由锁正确保护的字段中。
我的问题是:
为什么要点 3 有约束:“正确构造的对象”,而要点 2 没有?
以下代码是否安全地发布map实例?我认为代码符合要点 2 的条件。
public class SafePublish {
volatile DummyMap map = new DummyMap();
SafePublish() throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
// Safe to use 'map'?
System.out.println(SafePublish.this.map);
}
}).start();
Thread.sleep(5000);
}
public static void main(String[] args) throws InterruptedException {
SafePublish safePublishInstance = new SafePublish();
}
public …Run Code Online (Sandbox Code Playgroud) java concurrency volatile java-memory-model safe-publication
例如,JDK方法java.lang.Integer.numberOfLeadingZeros(int):
public static int numberOfLeadingZeros(int i) {
// HD, Figure 5-6
if (i == 0)
return 32;
int n = 1;
if (i >>> 16 == 0) { n += 16; i <<= 16; }
if (i >>> 24 == 0) { n += 8; i <<= 8; }
if (i >>> 28 == 0) { n += 4; i <<= 4; }
if (i >>> 30 == 0) { n += 2; i <<= 2; }
n -= i …Run Code Online (Sandbox Code Playgroud) 从http://hg.openjdk.java.net/jdk8/jdk8/hotspot/file/87ee5ee27509/src/share/vm/classfile/vmSymbols.hpp,我可以看到内部方法声明如下:
do_intrinsic(_getByte, sun_misc_Unsafe, getByte_name, getByte_signature, F_RN) \
Run Code Online (Sandbox Code Playgroud)
但是如何找到该方法的实际实现(我认为是汇编代码)_getByte?
原始代码是:
public static int numberOfLeadingZeros(int i) {
// HD, Figure 5-6
if (i == 0)
return 32;
int n = 1;
if (i >>> 16 == 0) { n += 16; i <<= 16; }
if (i >>> 24 == 0) { n += 8; i <<= 8; }
if (i >>> 28 == 0) { n += 4; i <<= 4; }
if (i >>> 30 == 0) { n += 2; i <<= 2; }
n -= i …Run Code Online (Sandbox Code Playgroud) java ×6
jvm ×3
openjdk ×3
jvm-hotspot ×2
concurrency ×1
hotspot ×1
intrinsics ×1
java-8 ×1
volatile ×1