Skip to content

Return false from a failed non-blocking flock on Windows - #10086

Merged
headius merged 1 commit into
jruby:jruby-10.0from
sferik:windows-flock-nonblocking
Nov 17, 2026
Merged

headius merged 1 commit into
jruby:jruby-10.0from
sferik:windows-flock-nonblocking

Conversation

@sferik

@sferik sferik commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Fixes #10085

On Windows, File#flock uses FileChannel#tryLock for LOCK_NB. When another process holds the lock, tryLock returns null, and PosixShim#tryLock returned without setting errno. So flock(File::LOCK_EX | File::LOCK_NB) raised a NullPointerException, and flock(File::LOCK_SH | File::LOCK_NB) returned 0 even though it didn't get the lock. Now tryLock sets EWOULDBLOCK and returns -1 for both, which RubyFile#flock already turns into false, the same as CRuby's flock(2) path.

I removed the windows: tag from the existing "returns false if trying to lock an exclusively locked file" spec and added one for the shared case. I tested on macOS with -Xnative.enabled=false, which takes the same FileChannel path as Windows. That reproduced both bugs before the fix. After it, every combination of exclusive and shared locks across two processes gives the same result as CRuby 3.4.12. mspec won't run with native disabled (it rejects the 0 umask), so I checked those cases with a script. The specs pass on CRuby and on JRuby with native enabled, in interpreter and JIT mode.

One thing I noticed but didn't change: tryLock releases the lock it already holds before trying the new one. So if upgrading a shared lock to exclusive fails, the file is left with no lock at all, where flock(2) would keep the shared lock.

Without native flock, which is always the case on Windows, File#flock
uses FileChannel#tryLock for LOCK_NB. That returns null when another
process holds the lock, and PosixShim#tryLock then returned without
setting errno. So LOCK_EX | LOCK_NB raised NullPointerException, and
LOCK_SH | LOCK_NB returned 0 though it didn't get the lock. Set
EWOULDBLOCK and return -1 for both, so flock returns false.

Fixes jruby#10085
@headius

headius commented Nov 17, 2026

Copy link
Copy Markdown
Member

Approved, as it's very simple and obviously NPE is not acceptable.

I'm super happy to entertain more improvements for Windows, including better CI testing.

@headius
headius merged commit b1ef084 into jruby:jruby-10.0 Nov 17, 2026
127 checks passed
@sferik

sferik commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

@headius should I open another PR against the master branch?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants