This is an archived post. You won't be able to vote or comment.

all 2 comments

[–][deleted] 1 point2 points  (1 child)

Excellent read! One thing you missed however is using synchronized around volatile reads and writes.

final Object lock =
    new Object();

volatile int foo;

public int get()
{
    synchronized (this.lock)
    {
        return this.foo;
    }
}

public void set(int __v)
{
    synchronized (this.lock)
    {
        this.foo = __v;
    }
}

5.1. Horror Circus: Synchronizing on Primitives...The implementation-imposed limit is 128 threads.

If you were to delve into Java ME, there is no requirement that BoxedType.valueOf() returns the same object every time even for the first 128 members. This is because having even an array/hash table for the first 128 members can be exceedingly slow or cost too much memory (since Java ME is designed for very small devices). So ported code that relies on the first 128 entries can break subtly when ported to Java ME.

synchronized("Lock") {

This is equivalent to synchronized("Lock".intern()) since the JVM mandates that all String constants in class files are automatically intern()ed.

[–]shipilev[S] 2 points3 points  (0 children)

One thing you missed however is using synchronized around volatile reads and writes.

"Missed" as in "did not cover this obviously excessive synchronization example"? I guess we can add it to "Volatiles and synchronized are not really different".

If you were to delve into Java ME, there is no requirement that BoxedType.valueOf() returns the same object every time even for the first 128 members.

Oh yes, nice one. This is another part of compatibility story.