Interruptible Sockets and TLS in Java: SocketChannel, Virtual Threads and SSLSocket
Cancel blocked network operations and secure connections: why interrupt doesn't unblock a Socket on a platform thread, SocketChannel and ClosedByInterruptException, virtual threads, then TLS with SSLSocket and SSLServerSocket, certificates, keystores, trust stores and SSLContext.
kvi5hnuCode Sprout team member9 min readOn this page
This article deals with two practical concerns of network programs. The first is cancellation: a user presses "Cancel" while a connection hangs, and the thread blocked in a socket read should give up. The second is security: traffic over the open Internet should be encrypted and the server authenticated, which means TLS.
Blocked threads and interrupts
A thread blocked in a socket read waits until data arrives, the connection closes, or a read timeout expires. In an interactive program, you'd like a third way out: cancel the operation by interrupting the thread. The concurrency chapter of Volume I showed that Thread.interrupt() makes blocking operations like sleep and wait throw InterruptedException. Socket I/O behaves differently depending on how it's done:
| Code | Effect of interrupt() while blocked in a read |
|---|---|
Socket streams on a platform thread | none; the thread stays blocked |
SocketChannel (any thread) | the channel is closed and the read throws ClosedByInterruptException |
Socket streams on a virtual thread | the socket is closed and the read throws SocketException ("Closed by interrupt") |
For a classic socket on a platform thread, the old workaround is to close the socket from another thread. That makes the blocked read fail with a SocketException. The demo shows all four cases against a server that sends three lines and then goes silent.
SocketChannel
The java.nio.channels package offers socket channels that are interruptible by design (an InterruptibleChannel). Opening one connects it:
SocketChannel channel = SocketChannel.open(new InetSocketAddress(host, port));
A channel has no streams. It reads into and writes from ByteBuffers (article 30). If you'd rather not deal with buffers, use the adapters:
var in = new Scanner(channel); // Scanner accepts a ReadableByteChannel
OutputStream out = Channels.newOutputStream(channel);
InputStream raw = Channels.newInputStream(channel);
When the thread is interrupted during a connect, read or write, the channel is closed and the operation throws ClosedByInterruptException. Note that the Scanner swallows that exception: hasNextLine simply returns false, and in.ioException() reveals what happened.
ServerSocketChannel is the server counterpart. Channels can also be put in non-blocking mode and multiplexed with a Selector. That's how high-performance servers handled many connections with few threads before virtual threads, and how frameworks such as Netty still work.
Virtual threads
Since Java 21, the simplest answer is to run blocking socket code on a virtual thread. The socket implementation then parks the virtual thread instead of blocking an operating system thread, and an interrupt closes the socket and wakes the reader up. Classic Socket code becomes cancellable with no changes. Structured concurrency and executor shutdown, which interrupt their threads, then work as expected for network code too.
Secure communication with TLS
Plain TCP traffic can be read and modified by anyone between the endpoints: on the Wi-Fi network, at the provider, along the route. Secure communication needs three things:
- Confidentiality: the data is encrypted, so third parties can't read it.
- Authentication: the client can verify that it's talking to the real server, not an impostor in the middle. The server proves its identity with a certificate. Optionally, the client can also present one (mutual TLS).
- Integrity: tampering with the data in transit is detected.
TLS (Transport Layer Security) provides all three. It's the successor of SSL, whose name survives in the Java package javax.net.ssl. The JDK supports TLS 1.3 and 1.2 by default. TLS 1.0, 1.1 and all SSL versions are disabled through the jdk.tls.disabledAlgorithms security property.
Secure sockets
Secure sockets come from factories:
SocketFactory factory = SSLSocketFactory.getDefault();
Socket s = factory.createSocket(host, port);
ServerSocketFactory serverFactory = SSLServerSocketFactory.getDefault();
ServerSocket server = serverFactory.createServerSocket(port);
The returned objects are SSLSocket and SSLServerSocket, subclasses of the familiar classes, so the rest of the code is unchanged: streams, accept, threads. The TLS handshake happens on the first read or write, or explicitly with startHandshake(). Afterwards, getSession() reports the negotiated protocol, cipher suite and the peer's certificates. To configure details, cast and use the TLS-specific methods. For example, ((SSLServerSocket) server).setNeedClientAuth(true) requires client certificates.
Certificates, keystores and trust stores
The server's certificate must be signed by a certificate authority (CA) that the client trusts. The JDK ships a list of well-known CAs in the trust store lib/security/cacerts. A production server gets its certificate from such a CA, for example through Let's Encrypt.
For testing, you can create a self-signed certificate with the JDK's keytool. Part 9 of this course covers certificates and keytool in depth.
keytool -genkeypair -alias server -keyalg EC -groupname secp256r1 \
-dname "CN=localhost" -ext san=dns:localhost,ip:127.0.0.1 \
-keystore server.p12 -storetype PKCS12 -storepass secret
The san (Subject Alternative Name) extension lists the names that host name verification accepts. The resulting keystore holds the server's private key and certificate. The client needs a trust store that contains the certificate, or the CA that signed it.
The default factories are configured with system properties:
java -Djavax.net.ssl.keyStore=server.p12 -Djavax.net.ssl.keyStorePassword=secret Server
java -Djavax.net.ssl.trustStore=client.p12 -Djavax.net.ssl.trustStorePassword=secret Client
To configure TLS in code, which is what the demo does, build an SSLContext from key managers (the identity you present) and trust managers (the identities you accept):
KeyStore keyStore = KeyStore.getInstance(path.toFile(), password);
var kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, password);
var tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLSocketFactory factory = context.getSocketFactory();
When connections fail, run with -Djavax.net.debug=ssl:handshake to see the handshake in detail.
The program
The demo starts a server that sends three lines and then stalls. Clients block on it in three ways: a socket on a platform thread, a SocketChannel, and a socket on a virtual thread. Each client is interrupted, and the program reports whether the thread was released. The platform-thread socket only gives up when the socket is closed from outside. A channel echo exchange follows. For TLS, the program runs keytool to create a short-lived self-signed certificate for localhost in a temporary directory, builds a server and a client SSLContext from it, and exchanges a message with host name verification turned on. A client using the JDK's default trust store rejects the self-signed certificate.
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.security.KeyStore;
import java.util.*;
import java.util.concurrent.*;
import javax.net.ssl.*;
public class Solution {
/** Sends 3 numbers, then pretends to be stuck (keeps the connection open but silent). */
static ServerSocket startStuckServer() throws IOException {
var server = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
Thread.ofVirtual().start(() -> {
while (!server.isClosed()) {
try {
Socket s = server.accept();
Thread.ofVirtual().start(() -> {
try (s; var out = new PrintWriter(s.getOutputStream(), true)) {
for (int i = 1; i <= 3; i++) out.println(i);
Thread.sleep(60_000); // stuck
} catch (IOException | InterruptedException e) { /* client went away */ }
});
} catch (IOException e) { /* server closed */ }
}
});
return server;
}
static void report(String label, Thread t, BlockingQueue<String> log) throws InterruptedException {
Thread.sleep(300); // let it reach the blocking read
t.interrupt();
t.join(1000);
System.out.printf("%-28s still blocked after interrupt: %-5b %s%n", label, t.isAlive(),
String.join(", ", drain(log)));
}
static List<String> drain(BlockingQueue<String> q) { var l = new ArrayList<String>(); q.drainTo(l); return l; }
public static void main(String[] args) throws Exception {
ServerSocket stuck = startStuckServer();
int port = stuck.getLocalPort();
var address = new InetSocketAddress(InetAddress.getLoopbackAddress(), port);
System.out.println("--- interrupting blocked reads ---");
// 1. classic Socket on a platform thread
var log = new LinkedBlockingQueue<String>();
var socketRef = new Socket[1];
Thread platform = Thread.ofPlatform().start(() -> {
try (var s = new Socket()) {
socketRef[0] = s;
s.connect(address);
var in = new Scanner(s.getInputStream());
int n = 0;
while (in.hasNextLine()) { in.nextLine(); n++; }
log.add("read " + n + " lines, then " + (in.ioException() == null ? "end" : in.ioException().getClass().getSimpleName()));
} catch (IOException e) {
log.add(e.getClass().getSimpleName());
}
});
report("Socket, platform thread:", platform, log);
socketRef[0].close(); // the workaround: close it from outside
platform.join();
System.out.println(" after close(): " + drain(log));
// 2. SocketChannel on a platform thread
Thread channelThread = Thread.ofPlatform().start(() -> {
try (SocketChannel channel = SocketChannel.open(address)) {
var in = new Scanner(channel); // Scanner reads from a ReadableByteChannel
int n = 0;
while (in.hasNextLine()) { in.nextLine(); n++; }
log.add("read " + n + " lines, then " + in.ioException().getClass().getSimpleName()
+ ", channel open: " + channel.isOpen());
} catch (IOException e) {
log.add(e.getClass().getSimpleName());
}
});
report("SocketChannel, platform:", channelThread, log);
// 3. classic Socket on a virtual thread
Thread virtual = Thread.ofVirtual().start(() -> {
try (var s = new Socket()) {
s.connect(address);
var in = new BufferedReader(new InputStreamReader(s.getInputStream()));
int n = 0;
while (in.readLine() != null) n++;
log.add("read " + n + " lines, end of stream");
} catch (IOException e) {
log.add(e.getClass().getSimpleName() + " (" + e.getMessage() + ")");
}
});
report("Socket, virtual thread:", virtual, log);
stuck.close();
System.out.println("--- writing to a channel ---");
try (var echo = ServerSocketChannel.open().bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0))) {
Thread.ofVirtual().start(() -> {
try (SocketChannel c = echo.accept()) {
ByteBuffer buf = ByteBuffer.allocate(64);
c.read(buf);
buf.flip();
c.write(buf);
} catch (IOException e) { /* ignore */ }
});
try (SocketChannel c = SocketChannel.open(echo.getLocalAddress())) {
OutputStream out = Channels.newOutputStream(c);
out.write("ping over a channel\n".getBytes(StandardCharsets.UTF_8));
System.out.println("echoed: " + new Scanner(c).nextLine());
}
}
System.out.println("--- TLS ---");
Path dir = Files.createTempDirectory("tls");
Path store = dir.resolve("server.p12");
char[] password = "secret".toCharArray();
try {
// a self-signed certificate for localhost and 127.0.0.1, made with the JDK's keytool
String keytool = Path.of(System.getProperty("java.home"), "bin", "keytool").toString();
Process p = new ProcessBuilder(keytool, "-genkeypair", "-alias", "server", "-keyalg", "EC",
"-groupname", "secp256r1", "-dname", "CN=localhost", "-validity", "2",
"-ext", "san=dns:localhost,ip:127.0.0.1", "-keystore", store.toString(),
"-storetype", "PKCS12", "-storepass", "secret").redirectErrorStream(true).start();
p.getInputStream().readAllBytes();
System.out.println("keytool exit code: " + p.waitFor());
KeyStore keyStore = KeyStore.getInstance(store.toFile(), password);
var kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, password);
SSLContext serverContext = SSLContext.getInstance("TLS");
serverContext.init(kmf.getKeyManagers(), null, null);
var tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore); // the client trusts exactly this certificate
SSLContext clientContext = SSLContext.getInstance("TLS");
clientContext.init(null, tmf.getTrustManagers(), null);
SSLServerSocketFactory ssf = serverContext.getServerSocketFactory();
try (var server = (SSLServerSocket) ssf.createServerSocket(0, 50, InetAddress.getLoopbackAddress())) {
Thread.ofVirtual().start(() -> {
for (int i = 0; i < 2; i++) {
try (Socket s = server.accept();
var in = new Scanner(s.getInputStream(), StandardCharsets.UTF_8);
var out = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8), true)) {
if (in.hasNextLine()) out.println("Echo: " + in.nextLine());
} catch (IOException e) { /* failed handshake */ }
}
});
try (var s = (SSLSocket) clientContext.getSocketFactory().createSocket("localhost", server.getLocalPort())) {
SSLParameters params = s.getSSLParameters();
params.setEndpointIdentificationAlgorithm("HTTPS"); // check the host name
s.setSSLParameters(params);
s.startHandshake();
SSLSession session = s.getSession();
System.out.println("protocol " + session.getProtocol() + ", peer " + session.getPeerPrincipal().getName());
var out = new PrintWriter(new OutputStreamWriter(s.getOutputStream(), StandardCharsets.UTF_8), true);
out.println("secret message");
System.out.println(new Scanner(s.getInputStream(), StandardCharsets.UTF_8).nextLine());
}
try (var s = (SSLSocket) SSLContext.getDefault().getSocketFactory().createSocket("localhost", server.getLocalPort())) {
s.startHandshake(); // default trust store: the JDK's CA list
} catch (SSLHandshakeException e) {
System.out.println("default trust store: SSLHandshakeException, self-signed certificate rejected");
}
}
} finally {
Files.deleteIfExists(store);
Files.delete(dir);
}
}
}
--- interrupting blocked reads ---
Socket, platform thread: still blocked after interrupt: true
after close(): [read 3 lines, then SocketException]
SocketChannel, platform: still blocked after interrupt: false read 3 lines, then ClosedByInterruptException, channel open: false
Socket, virtual thread: still blocked after interrupt: false SocketException (Closed by interrupt)
--- writing to a channel ---
echoed: ping over a channel
--- TLS ---
keytool exit code: 0
protocol TLSv1.3, peer CN=localhost
Echo: secret message
default trust store: SSLHandshakeException, self-signed certificate rejected
Common questions
How do I cancel a blocking socket read in a GUI or a timeout scenario?
The simplest options are a read timeout (setSoTimeout), running the code on a virtual thread and interrupting it, or using a SocketChannel. On a platform thread with a classic socket, close the socket from another thread.
What does "PKIX path building failed" mean?
The client doesn't trust the server's certificate chain: it's self-signed, signed by a private CA, or missing an intermediate certificate on the server. Import the CA certificate into a trust store your program uses (keytool -importcert), or fix the server's chain. Don't disable checking.
What does "No subject alternative names matching IP address found" mean?
Host name verification is on and the certificate wasn't issued for the name or IP you connected to. Connect with the name in the certificate, or issue a certificate that includes the name (-ext san=dns:...,ip:...).
Which keystore format should I use? PKCS12, the default since Java 9 and readable by other tools such as OpenSSL. The old JKS format is Java-only.
Should I still write SSLSocket code myself?
Rarely. HTTPS through the HTTP client (article 53) or a framework covers most needs. Use SSLSocket for your own TLS-protected protocols, and SSLEngine with non-blocking I/O when writing frameworks.
How do I enable TLS 1.0 or 1.1 to talk to an old server?
Remove them from jdk.tls.disabledAlgorithms in conf/security/java.security (or a properties file given with -Djava.security.properties), and only for the program that needs it. These versions are broken, and the server should be upgraded.
API reference
| API | Purpose |
|---|---|
SocketChannel.open(SocketAddress) | connected, interruptible socket channel |
ServerSocketChannel.open().bind(address), accept() | server channel |
Channels.newInputStream, newOutputStream, new Scanner(channel) | stream adapters for channels |
ClosedByInterruptException | the channel was closed because the thread was interrupted |
Thread.ofVirtual().start(task) | virtual threads make Socket I/O interruptible |
SSLSocketFactory.getDefault(), SSLServerSocketFactory.getDefault() | TLS sockets configured by system properties |
SSLContext.getInstance("TLS"), init(keyManagers, trustManagers, random) | TLS configured in code |
SSLContext.getSocketFactory(), getServerSocketFactory() | factories from a context |
KeyManagerFactory, TrustManagerFactory, KeyStore | identities and trusted certificates |
SSLSocket.startHandshake(), getSession() | handshake and session details |
SSLParameters.setEndpointIdentificationAlgorithm("HTTPS") | host name verification |
SSLServerSocket.setNeedClientAuth(true) | require client certificates |
Summary
- Interrupting a platform thread that is blocked in a
Socketread has no effect. Closing the socket from another thread works. SocketChanneloperations are interruptible and throwClosedByInterruptException. On virtual threads, plainSocketI/O is interruptible too.- TLS encrypts, authenticates the server through certificates, and protects integrity.
javax.net.sslprovidesSSLSocketandSSLServerSocket. - Servers need a keystore with their private key and certificate. Clients need a trust store with the trusted CAs. Configure them with system properties or an
SSLContext. - Turn on host name verification for raw TLS sockets, and never disable certificate checks.
Practice Questions
A desktop app reads from a Socket in a background platform thread. The Cancel button calls thread.interrupt(), but nothing happens. Give two fixes.
Socket streams on platform threads ignore interrupts. Either close the socket from the Cancel handler, which makes the blocked read throw a SocketException, or restructure the code to use an interruptible SocketChannel or to run on a virtual thread, where an interrupt closes the socket and wakes the reader.
Why does a Scanner reading from an interrupted SocketChannel not throw an exception?
Scanner catches IOExceptions from its source and treats them as the end of input, so hasNextLine() returns false. The exception, here a ClosedByInterruptException, is available from scanner.ioException().
What are the three guarantees TLS provides, and which one does a "trust all certificates" TrustManager destroy?
Confidentiality, authentication of the server (and optionally the client), and integrity. A trust-all manager destroys authentication: an attacker can present any certificate and act as a man in the middle, decrypting and re-encrypting the traffic, which defeats the other two guarantees as well.
What's the difference between a keystore and a trust store?
A keystore holds your own identity: a private key and its certificate chain, which a server presents to clients. A trust store holds certificates of parties you trust, usually certificate authorities, against which you check the certificates others present. Both use the same file formats (PKCS12 or JKS) and the KeyStore class.
A TLS client connects to api.example.com, and the server presents a valid certificate for evil.example.net signed by a trusted CA. Does a plain SSLSocket accept it?
Yes, unless host name verification is enabled. By default an SSLSocket checks only that the chain leads to a trusted CA. Setting the endpoint identification algorithm to "HTTPS" in the SSLParameters makes the handshake fail because the certificate's names don't include api.example.com. The HttpClient and HttpsURLConnection perform this check by default.
Previous: Java Server Sockets: Serving Multiple Clients with Threads and Virtual Threads
Next: URIs, URLs and URLConnection in Java: Retrieving Web Data and Headers
Related reading
- Java Server Sockets: Serving Multiple Clients with Threads and Virtual Threads
- Java File Locking: FileLock, Shared and Exclusive Locks
- Java Parallel Streams: When They Help, Ordering and Thread Safety
- Java Stream Gatherers: windowFixed, windowSliding, fold, scan and mapConcurrent
- Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.