changeset 2035:00bbfef1a86b acme-tiny

added Thread.try_synchronized
author Franklin Schmidt <fschmidt@gmail.com>
date Wed, 05 Nov 2025 11:20:47 -0700
parents d718511fc69f
children 2740f8a9ba3a
files src/luan/modules/Thread.luan src/luan/modules/ThreadLuan.java
diffstat 2 files changed, 25 insertions(+), 14 deletions(-) [+]
line wrap: on
line diff
diff -r d718511fc69f -r 00bbfef1a86b src/luan/modules/Thread.luan
--- a/src/luan/modules/Thread.luan	Tue Nov 04 20:28:50 2025 -0800
+++ b/src/luan/modules/Thread.luan	Wed Nov 05 11:20:47 2025 -0700
@@ -2,6 +2,8 @@
 local ThreadLuan = require "java:luan.modules.ThreadLuan"
 local ThreadJava = require "java:java.lang.Thread"
 local ReentrantLock = require "java:java.util.concurrent.locks.ReentrantLock"
+local TimeUnit = require "java:java.util.concurrent.TimeUnit"
+local MILLISECONDS = TimeUnit.MILLISECONDS
 local Luan = require "luan:Luan.luan"
 local error = Luan.error
 local new_error = Luan.new_error or error()
@@ -92,14 +94,35 @@
 
 
 local default_time_out = Time.period{minutes=10}
-local run_in_lock = ThreadLuan.runInLock
 local get_lock = ThreadLuan.getLock
 
 function Thread.synchronized(fn,key,time_out)
 	time_out = time_out or default_time_out
 	local lock = get_lock(key)
 	return function(...)
-		return run_in_lock(lock,time_out,fn,...)
+		if not lock.tryLock(time_out,MILLISECONDS) then
+			error "failed to acquire lock"
+		end
+		try
+			return fn.call(...)
+		finally
+			lock.unlock()
+		end
+	end
+end
+
+function Thread.try_synchronized(fn,key,time_out)
+	time_out = time_out or default_time_out
+	local lock = get_lock(key)
+	return function(...)
+		if not lock.tryLock(time_out,MILLISECONDS) then
+			return false
+		end
+		try
+			return true, fn.call(...)
+		finally
+			lock.unlock()
+		end
 	end
 end
 
diff -r d718511fc69f -r 00bbfef1a86b src/luan/modules/ThreadLuan.java
--- a/src/luan/modules/ThreadLuan.java	Tue Nov 04 20:28:50 2025 -0800
+++ b/src/luan/modules/ThreadLuan.java	Wed Nov 05 11:20:47 2025 -0700
@@ -223,18 +223,6 @@
 	}
 
 
-	public static Object runInLock(Luan luan,Lock lock,long timeout,LuanFunction fn,Object... args)
-		throws LuanException, InterruptedException
-	{
-		if( !lock.tryLock(timeout,TimeUnit.MILLISECONDS) )
-			throw new LuanException("failed to acquire lock");
-		try {
-			return fn.call(luan,args);
-		} finally {
-			lock.unlock();
-		}
-	}
-
 	private static final Map<String,Lock> locks = new WeakCacheMap<String,Lock>();
 
 	public static synchronized Lock getLock(String key) {