Created
May 15, 2023 16:10
-
-
Save franz1981/65a3eff93060189a31fa307f74428fa9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.net.*; | |
import java.util.*; | |
public class VirtualThreadExample { | |
public static void main(String[] args) throws Exception { | |
// Create a virtual executor for running virtual threads | |
VirtualThreadExecutor executor = VirtualThreadExecutor.newSingleVirtualThreadExecutor(); | |
// Start the echo server on a virtual thread | |
executor.execute(() -> { | |
try (ServerSocket serverSocket = new ServerSocket(5000)) { | |
System.out.println("Echo server is running..."); | |
while (true) { | |
Socket socket = serverSocket.accept(); | |
executor.execute(() -> { | |
try (BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); | |
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true)) { | |
String line; | |
while ((line = reader.readLine()) != null) { | |
System.out.println("Received: " + line); | |
writer.println(line); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
}); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
}); | |
// Start the client on a virtual thread | |
executor.execute(() -> { | |
try (Socket socket = new Socket("localhost", 5000)) { | |
System.out.println("Connected to echo server..."); | |
// Send random sequence of numbers | |
Random rand = new Random(); | |
int amount = 10; | |
for (int i = 0; i < amount; i++) { | |
int num = rand.nextInt(100); | |
System.out.println("Sending: " + num); | |
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); | |
writer.println(num); | |
} | |
// Wait for all the numbers to be echoed back | |
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); | |
for (int i = 0; i < amount; i++) { | |
String line = reader.readLine(); | |
System.out.println("Received: " + line); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
}); | |
// Shutdown the executor after both the server and client have finished | |
executor.awaitTermination(); | |
executor.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment