Reputation: 41
I have a 2 statement method in Java 8. The first statement takes a relatively long time to execute, and importantly, can't return a value. The second statement is quite quick. How do I execute and complete the first statement and ensure that the second statement does not execute until the first is done? A code snippet would be much appreciated.
public static Object returnMyClassFieldValue() {
setMyClassField(); // long running; can't return a value
return MyClass.valueOfMyField; // very quick
}
Upvotes: 0
Views: 1740
Reputation: 318
This code is executing sequentially, so the first statement gets executed first and after the statement finished the next gets executed.
The methodcall
setMyClassField()
returns after the method finished. So there is no additional code needed to run the code sequential.
If you want to run the method in a separate thread, you can use Threads and use the method
join()
to wait for execution or you use Thread Pools.
Threads: https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
Thread Pools: https://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html
Conclusion: You have nothing to do to run the second statement after the first one.
If that answeres your question.
Upvotes: 1