← Back to Advanced Java Course | Chapter 13: Java NIO | Lesson 3 of 5

Java में Async File I/O

AsynchronousFileChannel किसी program को एक read या write शुरू करने और तुरंत बाकी काम जारी रखने देता है, operation पूरा होने पर notify होने के लिए एक Future या CompletionHandler का उपयोग करते हुए।

What is Asynchronous File I/O?

Asynchronous file I/O किसी program को एक read या write operation शुरू करने और तुरंत बाकी काम जारी रखने देता है, calling thread को पूरे समय block करने के बजाय सिर्फ तभी notify होते हुए जब operation असल में पूरा हो।

उदाहरण: What is Asynchronous File I/O?

java
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Print a line to the console
		System.out.println("Async I/O starts an operation and continues, notified only on completion");
	}
}

AsynchronousFileChannel Basics

AsynchronousFileChannel, NIO.2 का हिस्सा, एक regular FileChannel की तरह ही खोला जाता है लेकिन non-blocking reads और writes को support करता है, और दूसरे NIO channels की तरह यह अब भी एक ByteBuffer में पढ़ता और उससे लिखता है।

उदाहरण: AsynchronousFileChannel Basics

java
// Import java.nio.channels.AsynchronousFileChannel so it can be used by its short name
import java.nio.channels.AsynchronousFileChannel;
// Import java.nio.file.* so it can be used by its short name
import java.nio.file.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) throws Exception {
		Path file = Files.createTempFile("demo", ".txt");
		AsynchronousFileChannel channel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
		// Print a line to the console
		System.out.println("Opened: " + channel.isOpen());
		channel.close();
		Files.delete(file);
	}
}

Reading Asynchronously with a Future

किसी AsynchronousFileChannel पर read call करना तुरंत एक Future return करता है, और calling thread बाकी code चलाना जारी रख सकता है, सिर्फ तभी block होते हुए जब वह बाद में असली result निकालने के लिए get() call करे।

उदाहरण: Reading Asynchronously with a Future

java
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.*;
import java.nio.ByteBuffer;
import java.util.concurrent.Future;
public class Main {
	public static void main(String[] args) throws Exception {
		Path file = Files.createTempFile("demo", ".txt");
		Files.writeString(file, "hello");
		AsynchronousFileChannel channel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
		ByteBuffer buffer = ByteBuffer.allocate(5);
		Future<Integer> future = channel.read(buffer, 0); // returns immediately
		future.get(); // blocks only here, when the result is needed
		System.out.println(new String(buffer.array()));
		channel.close();
		Files.delete(file);
	}
}

Reading Asynchronously with a CompletionHandler

एक CompletionHandler, Future का एक विकल्प है जो पूरी तरह blocking से बचता है: इसका completed method तब अपने आप call होता है जब operation सफल हो, result के साथ, और इसका failed method तब call होता है जब operation में कोई error आए।

उदाहरण: Reading Asynchronously with a CompletionHandler

java
// Import java.nio.channels.* so it can be used by its short name
import java.nio.channels.*;
// Import java.nio.file.* so it can be used by its short name
import java.nio.file.*;
import java.nio.ByteBuffer;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) throws Exception {
		Path file = Files.createTempFile("demo", ".txt");
		Files.writeString(file, "data");
		AsynchronousFileChannel channel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
		ByteBuffer buffer = ByteBuffer.allocate(4);
		channel.read(buffer, 0, null, new CompletionHandler<Integer, Void>() {
			public void completed(Integer result, Void attachment) {
				// Print a line to the console
				System.out.println("Read complete: " + new String(buffer.array()));
			}
			public void failed(Throwable exc, Void attachment) {
				// Print a line to the console
				System.out.println("Failed: " + exc.getMessage());
			}
		});
		Thread.sleep(100);
		channel.close();
		Files.delete(file);
	}
}

Writing Asynchronously

Asynchronous writes asynchronous reads जैसे ही काम करते हैं, एक Future return करते हुए या एक CompletionHandler accept करते हुए, और operation तभी पूरा माना जाता है जब data असल में underlying file में लिख दिया गया हो।

उदाहरण: Writing Asynchronously

java
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.*;
import java.nio.ByteBuffer;
public class Main {
	public static void main(String[] args) throws Exception {
		Path file = Files.createTempFile("demo", ".txt");
		AsynchronousFileChannel channel = AsynchronousFileChannel.open(file, StandardOpenOption.WRITE);
		ByteBuffer buffer = ByteBuffer.wrap("async write".getBytes());
		channel.write(buffer, 0).get(); // complete once actually written
		channel.close();
		System.out.println(Files.readString(file));
		Files.delete(file);
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. asynchronous operation पूरा होने से पहले main को खत्म होने देना, जिससे result कभी print नहीं होता।
  2. read शुरू करने के तुरंत बाद future.get() call करना, जो block करता है और async I/O का फायदा हटा देता है।
  3. यह भूल जाना कि async read और write को एक file position argument चाहिए और यह कि किसी buffer का data उपयोग होने से पहले उसे flip करना चाहिए।
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.