Multithreading in Jeamlit
Jeamlit uses threads within its architecture, which can make it difficult for app developers to include their own multithreaded processes.
Note
Jeamlit Threading experience is a work in progress. Reach out on the forum for any question.
Here is the current state:
- ❌
Jt.
commands in Threads are not supported ❌// DON'T - will throw an exception new Thread( () -> {Jt.text("Hello").use();} ).start();
- ❌ non-daemon threads can outlive the app run and leak ... ❌
// DON'T - the scheduler will run forever - one new scheduler will be recreated at every app run ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(() -> {...}, 10, 10, TimeUnit.SECONDS)
- ✅ ... but in some cases it's ok ✅
// DANGEROUS but ok-ish - will complete eventually - using Threads for logging/tracing/metrics purpose is ok new Thread(() -> {System.out.println("Log some traces")}).start();
- ✅ Compute/IO in threads is supported, but make sure to complete all threads and shutdown the scheduler ✅
// OK - background computation, render results on main thread ExecutorService executor = Executors.newFixedThreadPool(4); try { List<Future<String>> futures = new ArrayList<>(); for (int i = 0; i < 5; i++) { final int taskId = i; futures.add(executor.submit(() -> { // ✅ Can do computation/IO here Thread.sleep(1000); return "Task " + taskId + " completed"; })); } // Collect results and display on main thread for (Future<String> future : futures) { String result = future.get(); // Wait for result Jt.text(result).use(); // ✅ Safe - on main thread } } catch (ExecutionException e) { throw new RuntimeException(e); } finally { executor.shutdown(); // Always clean up }
Still have questions?
Go to our discussions forum for helpful information and advice from Jeamlit experts.