How does Java's record class implement synchronization?

354 views Asked by At

Since Record class instance does not have the obj header which common Object instance has. But we can still use synchronization features like:

public record User(long id, String name, int age) {}

User user = new User(1, "name", 18);
synchronized (user) {
    user.wait();
    System.out.println("test");
}

Would there be a process like common Object instance from light weight lock to heavy lock transformation?

1

There are 1 answers

0
Brian Goetz On BEST ANSWER

Java's record classes are ordinary classes, with an object identity and all the things that come with them (like a monitor.)

That said, if you find yourself synchronizing on a record, you're probably doing something wrong; the state of records is shallowly immutable (all fields are final), so it's not clear why you would be locking on the record.