약속, 퓨처 및 비동기 작업
장시간 실행되는 작업과 비차단 입출력을 처리하기 위한 Clojure 비동기 프로그래밍 패턴을 살펴봅니다.
약속, 퓨처 및 비동기 작업은(는) CoddyKit의 무료 Clojure Functional Programming & JVM Backend Development 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Clojure Functional Programming & JVM Backend Development 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Clojure Functional Programming & JVM Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Intro to Asynchronous Programming
Welcome! In this lesson, we'll explore asynchronous programming in Clojure. This is key for building responsive applications that don't freeze while waiting for long tasks.
Asynchronous tasks run in the 'background', allowing your main program to continue without interruption. When the background task finishes, it delivers its result.
Blocking vs. Non-Blocking
Imagine fetching data from a slow server. A blocking operation would make your application wait until the data arrives. During this time, nothing else can happen.
A non-blocking operation starts the fetch but immediately returns control to your application. Your app can then do other things, and process the data once it's available.
Clojure's 'future' Macro
Clojure provides the future macro to run a computation on a separate thread. This makes the computation asynchronous and non-blocking from the caller's perspective.
The future immediately returns a 'future' object, which is a placeholder for the eventual result.
Using 'future' for Async Tasks
Let's see future in action. We'll simulate a long-running task using Thread/sleep. Notice how the "Future started" message appears instantly.
(ns my-app.core
(:gen-class))
(defn -main
"Demonstrates a simple future."
[& args]
(println "Main thread: Starting future...")
(let [f (future
(println " Future thread: Working...")
(Thread/sleep 2000) ; Simulate work
(println " Future thread: Done!")
"Result from Future")]
(println "Main thread: Future started, continuing...")
; We'll learn how to get the result next!
(Thread/sleep 1000) ; Let main thread do other work
(println "Main thread: End of main.")))Getting Results from 'future'
To get the actual value from a future, you dereference it. You can use the @ reader macro or the deref function.
If the future's computation isn't finished yet, dereferencing will block the current thread until the result is ready.
(ns my-app.core
(:gen-class))
(defn -main
"Dereferencing a future."
[& args]
(println "Main thread: Starting future...")
(let [f (future
(println " Future thread: Working...")
(Thread/sleep 2000)
"Long Task Complete")]
(println "Main thread: Future launched.")
(println "Main thread: Doing other work...")
(Thread/sleep 500)
(println "Main thread: Now waiting for future result...")
(let [result @f] ; Dereference the future
(println "Main thread: Future result:" result))
(println "Main thread: All done!")))Clojure's 'promise' Function
While future runs a computation, a promise is a placeholder for a value that will be delivered later, usually by another thread or an external event.
Think of it as an empty box that someone else will fill. You can wait for the box to be filled by dereferencing it.
Delivering and Dereferencing a Promise
The deliver function is used to put a value into a promise. Once a promise is delivered, its value cannot be changed.
Dereferencing a promise works just like a future: it will block until a value is delivered.
(ns my-app.core
(:gen-class))
(defn -main
"Delivering and dereferencing a promise."
[& args]
(let [p (promise)]
(println "Main thread: Created a promise.")
(future
(println " Future thread: Doing async work...")
(Thread/sleep 1500)
(let [val "Value from Future!"]
(println " Future thread: Delivering value to promise.")
(deliver p val)))
(println "Main thread: Waiting for promise to be delivered...")
(let [result @p] ; Blocks until 'deliver' is called
(println "Main thread: Promise received:" result))
(println "Main thread: Program finished.")))Future and Promise Together
future and promise often work together. A future might perform a complex calculation, and then deliver its result to a promise, which can then be picked up by another part of your application.
This pattern is useful for coordinating between different asynchronous tasks or threads.
(ns my-app.core
(:gen-class))
(defn long-calculation []
(println " Calculation: Starting...")
(Thread/sleep 2500) ; Simulate heavy work
(println " Calculation: Finished.")
(* 123 456))
(defn -main
"Coordinating with future and promise."
[& args]
(let [calc-promise (promise)]
(println "Main: Kicking off calculation...")
(future ; Run calculation in a separate thread
(let [result (long-calculation)]
(deliver calc-promise result)))
(println "Main: Calculation started. Doing other things...")
(Thread/sleep 1000)
(println "Main: Still doing other things...")
(println "Main: Waiting for calculation result...")
(let [final-result @calc-promise]
(println "Main: Received final result:" final-result))
(println "Main: Done.")))Error Handling with Async Tasks
When an exception occurs inside a future or before a promise is delivered, dereferencing the future/promise will re-throw that exception on the dereferencing thread.
This allows you to handle errors in your main thread, even if they originate from an asynchronous task.
Quick Check: Async Behavior
Consider the following Clojure code snippet:
(let [f (future (Thread/sleep 1000) "Async Result")]
(println "Started")
(Thread/sleep 500)
(println "Waiting...")
(let [result @f]
(println "Got:" result)))
What is the *minimum* total time before "Got: Async Result" is printed?
Recap: Promises, Futures & Async
- Asynchronous programming allows tasks to run without blocking the main program flow.
- Clojure's
futuremacro runs a computation on a separate thread, returning a placeholder immediately. - The
promisefunction creates a placeholder that can bedelivered a value later, often from another thread or external source. - Both
futureandpromiseare dereferenced (using@orderef) to retrieve their values, blocking if the value isn't ready. - Exceptions in async tasks are re-thrown when dereferenced.
자주 묻는 질문
“약속, 퓨처 및 비동기 작업” 강의는 무료인가요?
네 — “약속, 퓨처 및 비동기 작업” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Clojure Functional Programming & JVM Backend Development 강의 전체를 잠금 해제할 수 있습니다. Clojure Functional Programming & JVM Backend Development 강의에는 총 4개의 강의가 포함되어 있습니다.
“약속, 퓨처 및 비동기 작업”에서 뭘 배우나요?
장시간 실행되는 작업과 비차단 입출력을 처리하기 위한 Clojure 비동기 프로그래밍 패턴을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 Clojure Functional Programming & JVM Backend Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Clojure Functional Programming & JVM Backend Development을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Clojure Functional Programming & JVM Backend Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“약속, 퓨처 및 비동기 작업” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Clojure Functional Programming & JVM Backend Development 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Clojure Functional Programming & JVM Backend Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.