2

Here is singleton session bean example from Java EE tutorial:

@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER) 
@Singleton
public class ExampleSingletonBean {

    private String state;

    @Lock(LockType.READ)
    public String getState() {
        return state;
    }

    @Lock(LockType.WRITE)
    public void setState(String newState) {
        state = newState;
    }
}

How it is possible that private String state field don't have to be volatile? How application server can guarantee that this reference never be cached thread-locally for different, simultaneous HTTP requests?

tung
  • 719
  • 2
  • 14
  • 30
Rafal
  • 1,498
  • 5
  • 15
  • 20

1 Answers1

1

As described here, when you use a CONTAINER, a Lock is used.

Now the lock itself somehow emulates volatile, as can be read here:

All Lock implementations must enforce the same memory synchronization semantics as provided by the built-in monitor lock, as described in The Java Language Specification, Third Edition (17.4 Memory Model):

  • A successful lock operation has the same memory synchronization effects as a successful Lock action.
  • A successful unlock operation has the same memory synchronization effects as a successful Unlock action.

In other words, the implicit lock is "volatile" (perhaps not necessarily by keyword, but by implementation).

Community
  • 1
  • 1
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555