Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized Methods in Java IO Streams

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?

like image 839
Antonio Avatar asked Nov 04 '15 15:11

Antonio


People also ask

What are synchronized methods in Java?

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.

How many threads per instance can execute inside a synchronized instance method?

Only one thread per instance can execute inside a synchronized instance method.

What is synchronized method and synchronized block?

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.


1 Answers

There are a few contradictory facts pointing that synchronized keyword is just a mistake here:

  1. For sure it is just a hint for developers. Methods are empty and synchronized keyword is not inherited in subclasses.

  2. 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.

  3. Many of the JDK stream implementations have incoherent usage of synchronized keywords.

  4. 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.

like image 69
AdamSkywalker Avatar answered Sep 30 '22 09:09

AdamSkywalker