What Is the Purpose of Flush() in Java Streams

What is the purpose of flush() in Java streams?

From the docs of the flush method:

Flushes the output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

The buffering is mainly done to improve the I/O performance. More on this can be read from this article: Tuning Java I/O Performance.

When to use flush() in java?

When to use flush method and why do we use it?

It flushes anything which is still buffered by the OutputStream. A detailed description is available in JavaDoc.


What does close method carry a score here?

I'm not sure what you mean by 'carry a score', but the close method finally closes resources (Input or Output), it releases e.g. file handles. You should always call close in a finally block to clean up all references the OS may have.

InputStream is = null;
try {
is = new FileInputStream(...);
// do stuff
} catch (IOException e) {
// do stuff
} finally {
if (is != null) {
is.close();
}
}

myObj2 = (John) ois.readObject(); ... please correct me if i am wrong,
i am reading the file object and storing into another object and
typecasting the file object.

Somehow correct, you deserialize an Object writen to the file before. Those files are proprietary and can only be understood by Java, so you last question is a good one!


What are the alternatives of Serialization or persisting the data in
Java. I don't want the data to get into file as byte stream.

You have a number of options. For client application you may want to use XML, JSON, or a lightweight database like SQLlite. On server-side you may have a look at more robust databases (e.g. MySQL) as well.

What is meant by 'flushing the stream'?

Flushing a stream ensures that all data that has been written to that stream is output, including clearing any that may have been buffered.

Some streams are buffered to aid performance, e.g. a stream writing to disk may buffer until the content reaches a block size.

Difference Between flush() vs reset() in JAVA

Why is reset method used if memory cache is wiped by flush method?

flush() will write the buffer of the ObjectOutputStream object in the underlying OutputStream but it will not reset the whole state of the ObjectOutputStream object.

If you open the ObjectOutputStream source code class, you can see that beyond the buffer it contains many instance fields.

Here is a little snippet :

/** filter stream for handling block data conversion */
private final BlockDataOutputStream bout;
/** obj -> wire handle map */
private final HandleTable handles;
/** obj -> replacement obj map */
private final ReplaceTable subs;
/** recursion depth */
private int depth;
/** buffer for writing primitive field values */
private byte[] primVals;

Some handle the conversion, others handle the cache, and so for...
ObjectOutputStream.reset() will have effects on this state :

Reset will disregard the state of any objects already written to the
stream.

and

Objects previously written to the stream will not be referred to as
already being in the stream. They will be written to the stream again.

These detail matter as ObjectOutputStream uses a reference sharing mechanism.

So writing in the stream multiple times the same object but with a different state will write the object with the original state multiple times.

The top level documentation of ObjectOutputStream explains that and more (emphasis is mine) :

The default serialization mechanism for an object writes the class of
the object, the class signature, and the values of all non-transient
and non-static fields. References to other objects (except in
transient or static fields) cause those objects to be written also.
Multiple references to a single object are encoded using a reference
sharing mechanism so that graphs of objects can be restored to the
same shape as when the original was written
.

You should now understand the reset() meaning.


Example illustrating a cache issue with ObjectOutputStream:

Execute this class that write 10 times the same object but with a different state i nan ObjectOutputStream without invoking reset() between the writings :

public class FlushAndReset {

public static void main(String[] args) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);

Foo foo = new Foo();
for (int i = 0; i < 10; i++) {
foo.setValue(i);
oos.writeObject(foo);
oos.flush();
// oos.reset();
}

ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
for (int i = 0; i < 10; i++) {
Object obj = ois.readObject();
System.out.println(obj);
}
}
}

With Foo defined as :

public class Foo implements Serializable {

private int value;

public void setValue(int value) {
this.value = value;
}

@Override
public String toString() {
return "Foo [value=" + value + "]";
}

}

As you will read the content of the BOS you will get :

Foo [value=0]

Foo [value=0]

Foo [value=0]

Foo [value=0]

Foo [value=0]

Foo [value=0]

Foo [value=0]

Foo [value=0]

Foo [value=0]

Foo [value=0]

Uncomment the reset() and you should see the change :

Foo [value=0]

Foo [value=1]

Foo [value=2]

Foo [value=3]

Foo [value=4]

Foo [value=5]

Foo [value=6]

Foo [value=7]

Foo [value=8]

Foo [value=9]

flush in java.io.FileWriter

Writers and streams usually buffer some of your output data in memory and try to write it in bigger blocks at a time. flushing will cause an immediate write to disk from the buffer, so if the program crashes that data won't be lost. Of course there's no guarantee, as the disk may not physically write the data immediately, so it could still be lost. But then it wouldn't be the Java program's fault :)

PrintWriters auto-flush (by default) when you write an end-of-line, and of course streams and buffers flush when you close them. Other than that, there's flushing only when the buffer is full.

Why is it necessary to flush the output buffer when it was just created?

This is needed when using either ObjectInputStream and ObjectOutputStream, because they send a header over the stream before the first write is called. The call to flush() will send that header to the remote side.

According to the spec, the header exists of the following contents:

magic version

If the header doesn't arrive at the moment a ObjectInputStream is build, this call will hang until it received the header bytes.

This means that if the protocol in question is written with ObjectStreams, it should flush after creating a ObjectOutputStream.

difference between flush and close function in case of filewriter in java

flush() writes the content of the buffer to the destination and makes the buffer empty for further data to store but it does not closes the stream permanently. That means you can still write some more data to the stream.

But close() closes the stream permanently. If you want to write some data further, then you have to reopen the stream again and append the data with the existing ones.

Should I also flush() a stream when I'm done with it, or is close() enough?

Close will automatically flush your stream, so yoou dont have to flush the stream while closing. Flush is useful when you are in the middle of writing to a stream and want to push the intermediate values to the file/output stream, so that if the program crashes the data wont be lost.

From Java 7 and higher you can make use of try-with-resources to avoid writing the clean up code for cleaning up the streams.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.



Related Topics



Leave a reply



Submit