Sitemap
Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Introduction to Actors in Swift.

--

In this article, we will discuss the newly released Actors in swift 5.5.

Concurrency is a major part of any Mobile Development Platform, we use concurrent tasks at almost every stage in our Application life Cycle. For example, updating a UI after we have received a response from our API or updating a model after any specif task is completed, etc.

Talking of concurrencies from a developer point of view, Queues are to be mentioned. Queues are closures that work on different and appropriate threads according to their orders.
Queues follow (FIFO) if deployed on multiple threads following concurrency.

Let's talk about the type of Queues we have.
Queues can be specified into two basic types.

Type of Queues:

  1. Serial Queue: Serial queues work in order. It pulls out the first task from the queue, starts working on it, operates on it until it has completed its execution, and then only picks up the new task.
  2. Concurrent Queue: Like Serial queues, it also pulls up the first task from the queue and initiates its execution in any thread that is available.
    If the system sees that it has access to more threads, it will pull out other tasks from the queue and initiate them on another thread without waiting for the first execution to be completed. Similarly, it works on any available number of tasks in a queue.

Concurrent Methods:

There are two types of methods available when working with queues

  1. Sync: Returns the control to the current queue after the whole execution of a particular task is completed blocking the whole queue.
  2. Async: Returns the control to the current queue immediately after initiating a particular task without waiting for it to end, thus it never blocks the whole queue.

So now we have generally talked about Concurrency. Let's assume we have a shared reference working under concurrent tasks like updating a string array.
Let's look at an example of doing it the conventional way.

In this example, we can see that the shared string array is being shared by multiple threads trying to update it.
We have no guarantee of which thread will finish fetching first and fall into the completion block.
Let's say our second task gets completed first and after its completion, we are trying to remove an element from 1st position and currently we have no element in the first position, so we can expect a crash here.
Or if we are performing another task we can have a race condition.

Data race makes concurrency Hard. It occurs when we have multiple threads accessing/modifying the same data.

We can avoid Data Races using value Types like structs for example

Although now our code is safe but the behavior is not correct.

This is where Actors come in.
Let's discuss some main features of Actors before we run on a code example.

ACTORS:

Conceptually similar to classes. Safe to use in concurrent environments because Swift ensures that a mutable state inside your actor is only ever accessed by a single thread at any given time, which helps eliminate a variety of serious bugs right at the compiler level.

  1. Actors are created using the new actor keyword. This is a new concrete nominal type in Swift, joining structs, classes, and enums.
  2. Actors are reference types.
  3. Actor isolates data.

Let's take an example of a class for executing concurrent code. This code will run absolutely fine in a single-threaded environment, but if this code is executed in a multi-threaded environment we will have a race condition.

Let's assume in a multi-threaded environment two threads execute manageEmployeeSalary method at the same time. Both our threads will transfer the salary to the same employee.

That’s definitely beneficial for the employee but not for the company.

Let's consider this through Actors.

What is happening here is another admin from outside of the actor is trying to do some modification in our first admin’s business.
Our compiler straight away gives an error “Hey you can not do this outside the actor unless you wait for the current task to be finished and then you can do it.”
So now we know we can not have race conditions because our compiler does not allow multiple threads to access a single resource at a single time.
How cool is that?

So how can we solve this problem??

Well, we have to wait using await keyword for one particular salary transfer to be completed, and then only we can transfer salary to any other employee.
We make sure salary is transferred and based on the result we remove the employee from our employee list.
This way we will never transfer the salary twice to a single employee.

So now our shared resource employee can never be modified in different threads at a time.

actors make sure that they are only modified once at a time.

Sorry employees no more good days.

There are several things to notice in this example.

  1. Actors are created using the new “actor” keyword
  2. The manageEmployeeSalary method is marked with async, because it will need to suspend its work while waiting for the transfer to complete.
  3. Although the transferSalaryToEmployee method is not marked with async, we still need to call it await because it will wait until anotherAdmin actor is able to handle the request.

Actor & classes both are reference types, but actors are safe shared states, unlike classes. Both of them share every aspect of each other except classes can be inherited.

@MainActor is the new keyword that makes sure that your code runs on the main thread. Also, we can do it this way if we want to make sure that we save our data on the main thread.

I guess we now have a basic idea of how actors work and when they can be used. That's it for this article now.
Please let me know if you have any questions!

Happy Coding!
Sheeraz Ahmed

--

--

Nerd For Tech
Nerd For Tech

Published in Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Sheeraz Ahmed
Sheeraz Ahmed

Written by Sheeraz Ahmed

Software Engineer | Mobile Apps

Responses (1)