Threaded code blocks

Another type of code blocks available in SubScript as operands along the normal code block is a threaded code block. In contrast to normal code, threaded code is executed from a dedicated thread by the virtual machine. You should use threaded code if you need to run a long-lasting operation from SubScript. If you run it from a normal code block, the SubScript VM’s main thread will be blocked by this task and it won’t be able to run anything else.

The syntax for the threaded code is as follows:

{* any normal Scala code here *}

That is, you place any valid Scala code between the {* and *}.

For example, compare the following two scripts:

script normalCode   = {  Thread.sleep(Long.MaxValue)  } || [println("Hello") ; println("World")]
script threadedCode = {* Thread.sleep(Long.MaxValue) *} || [println("Hello") ; println("World")]

The normalCode script will output nothing. The first operand of the || operator takes too long to execute and will block the main SubScript VM thread. In contrast, the threadedCode will output “Hello World” and will terminate successfully. Here, the long-running operation is wrapped into a threaded code block, {* *}, is executed from a dedicated thread, and, hence SubScript VM main thread is free to process the right hand side operand of the || operator.

In general, you should always use the threaded code block if you want to launch a long-running operation using a Scala code.

Leave a Reply