In Java since Java 1.0 in class java.io.InputStream
there are methods
public synchronized void mark(int readlimit) {}
and
public synchronized void reset() throws IOException { throw new IOException("mark/reset not supported"); }
Why are those two methods synchronized while all the others are not?
Synchronized methods enable a simple strategy for preventing thread interference and memory consistency errors: if an object is visible to more than one thread, all reads or writes to that object's variables are done through synchronized methods.
Only one thread per instance can execute inside a synchronized instance method.
synchronized method acquires a lock on the whole object. This means no other thread can use any synchronized method in the whole object while the method is being run by one thread. synchronized blocks acquires a lock in the object between parentheses after the synchronized keyword.
There are a few contradictory facts pointing that synchronized keyword is just a mistake here:
For sure it is just a hint for developers. Methods are empty and synchronized
keyword is not inherited in subclasses.
On the other hand, other methods are not synchronized, even abstract and empty methods. That means we were warned not to forget about synchronization on mark/reset, but we were not warned about concurrent read()
calls. That does not make sense because concurrent read will not work without synchronization.
Many of the JDK stream implementations have incoherent usage of synchronized keywords.
java.io.InputStream
being put opposite to java.nio.Buffer
has almost no useful basic method implementations but was made a class. So it tries to balance between this 'skeleton providing' and declaring general method contracts.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With