What’s @concurrent in Swift 6.2? – Donny Wals

0
1
What’s @concurrent in Swift 6.2? – Donny Wals


Swift 6.2 is obtainable and it comes with a number of enhancements to Swift Concurrency. Certainly one of these options is the @concurrent declaration that we are able to apply to nonisolated capabilities. On this submit, you’ll study a bit extra about what @concurrent is, why it was added to the language, and when you have to be utilizing @concurrent.

Earlier than we dig into @concurrent itself, I’d like to offer just a little little bit of context by exploring one other Swift 6.2 function referred to as nonisolated(nonsending) as a result of with out that, @concurrent wouldn’t exist in any respect.

And to make sense of nonisolated(nonsending) we’ll return to nonisolated capabilities.

Exploring nonisolated capabilities

A nonisolated operate is a operate that’s not remoted to any particular actor. In case you’re on Swift 6.1, otherwise you’re utilizing Swift 6.2 with default settings, that signifies that a nonisolated operate will at all times run on the worldwide executor.

In additional sensible phrases, a nonisolated operate would run its work on a background thread.

For instance the next operate would run away from the primary actor always:

nonisolated 
func decode(_ knowledge: Knowledge) async throws -> T {
  // ...
}

Whereas it’s a handy option to run code on the worldwide executor, this habits will be complicated. If we take away the async from that operate, it’s going to at all times run on the callers actor:

nonisolated 
func decode(_ knowledge: Knowledge) throws -> T {
  // ...
}

So if we name this model of decode(_:) from the primary actor, it’s going to run on the primary actor.

Since that distinction in habits will be sudden and complicated, the Swift crew has added nonisolated(nonsending). So let’s see what that does subsequent.

Exploring nonisolated(nonsending) capabilities

Any operate that’s marked as nonisolated(nonsending) will at all times run on the caller’s executor. This unifies habits for async and non-async capabilities and will be utilized as follows:

nonisolated(nonsending) 
func decode(_ knowledge: Knowledge) async throws -> T {
  // ...
}

Everytime you mark a operate like this, it not routinely offloads to the worldwide executor. As an alternative, it’s going to run on the caller’s actor.

This doesn’t simply unify habits for async and non-async capabilities, it additionally makes our much less concurrent and simpler to cause about.

Once we offload work to the worldwide executor, which means we’re primarily creating new isolation domains. The results of that’s that any state that’s handed to or accessed within our operate is probably accessed concurrently if now we have concurrent calls to that operate.

Which means that we should make the accessed or passed-in state Sendable, and that may turn out to be fairly a burden over time. For that cause, making capabilities nonisolated(nonsending) makes quite a lot of sense. It runs the operate on the caller’s actor (if any) so if we cross state from our call-site right into a nonisolated(nonsending) operate, that state doesn’t get handed into a brand new isolation context; we keep in the identical context we began out from. This implies much less concurrency, and fewer complexity in our code.

The advantages of nonisolated(nonsending) can actually add up which is why you may make it the default in your nonisolated operate by opting in to Swift 6.2’s NonIsolatedNonSendingByDefault function flag.

When your code is nonisolated(nonsending) by default, each operate that’s both explicitly or implicitly nonisolated shall be thought-about nonisolated(nonsending). Which means that we want a brand new option to offload work to the worldwide executor.

Enter @concurrent.

Offloading work with @concurrent in Swift 6.2

Now that you already know a bit extra about nonisolated and nonisolated(nonsending), we are able to lastly perceive @concurrent.

Utilizing @concurrent makes most sense once you’re utilizing the NonIsolatedNonSendingByDefault function flag as effectively. With out that function flag, you’ll be able to proceed utilizing nonisolated to attain the identical “offload to the worldwide executor” habits. That stated, marking capabilities as @concurrent can future proof your code and make your intent specific.

With @concurrent we are able to be sure that a nonisolated operate runs on the worldwide executor:

@concurrent
func decode(_ knowledge: Knowledge) async throws -> T {
  // ...
}

Marking a operate as @concurrent will routinely mark that operate as nonisolated so that you don’t have to write down @concurrent nonisolated. We are able to apply @concurrent to any operate that doesn’t have its isolation explicitly set. For instance, you’ll be able to apply @concurrent to a operate that’s outlined on a important actor remoted sort:

@MainActor
class DataViewModel {
  @concurrent
  func decode(_ knowledge: Knowledge) async throws -> T {
    // ...
  }
}

And even to a operate that’s outlined on an actor:

actor DataViewModel {
  @concurrent
  func decode(_ knowledge: Knowledge) async throws -> T {
    // ...
  }
}

You’re not allowed to use @concurrent to capabilities which have their isolation outlined explicitly. Each examples under are incorrect for the reason that operate would have conflicting isolation settings.

@concurrent @MainActor
func decode(_ knowledge: Knowledge) async throws -> T {
  // ...
}

@concurrent nonisolated(nonsending)
func decode(_ knowledge: Knowledge) async throws -> T {
  // ...
}

Figuring out when to make use of @concurrent

Utilizing @concurrent is an specific declaration to dump work to a background thread. Be aware that doing so introduces a brand new isolation area and would require any state concerned to be Sendable. That’s not at all times a straightforward factor to tug off.

In most apps, you solely need to introduce @concurrent when you’ve got an actual challenge to resolve the place extra concurrency helps you.

An instance of a case the place @concurrent ought to not be utilized is the next:

class Networking {
  func loadData(from url: URL) async throws -> Knowledge {
    let (knowledge, response) = attempt await URLSession.shared.knowledge(from: url)
    return knowledge
  }
}

The loadData operate makes a community name that it awaits with the await key phrase. That signifies that whereas the community name is energetic, we droop loadData. This enables the calling actor to carry out different work till loadData is resumed and knowledge is obtainable.

So once we name loadData from the primary actor, the primary actor could be free to deal with consumer enter whereas we look forward to the community name to finish.

Now let’s think about that you simply’re fetching a considerable amount of knowledge that it’s essential to decode. You began off utilizing default code for every thing:

class Networking {
  func getFeed() async throws -> Feed {
    let knowledge = attempt await loadData(from: Feed.endpoint)
    let feed: Feed = attempt await decode(knowledge)
    return feed
  }

  func loadData(from url: URL) async throws -> Knowledge {
    let (knowledge, response) = attempt await URLSession.shared.knowledge(from: url)
    return knowledge
  }

  func decode(_ knowledge: Knowledge) async throws -> T {
    let decoder = JSONDecoder()
    return attempt decoder.decode(T.self, from: knowledge)
  }
}

On this instance, all of our capabilities would run on the caller’s actor. For instance, the primary actor. Once we discover that decode takes quite a lot of time as a result of we fetched a complete bunch of knowledge, we are able to determine that our code would profit from some concurrency within the decoding division.

To do that, we are able to mark decode as @concurrent:

class Networking {
  // ...

  @concurrent
  func decode(_ knowledge: Knowledge) async throws -> T {
    let decoder = JSONDecoder()
    return attempt decoder.decode(T.self, from: knowledge)
  }
}

All of our different code will proceed behaving prefer it did earlier than by operating on the caller’s actor. Solely decode will run on the worldwide executor, guaranteeing we’re not blocking the primary actor throughout our JSON decoding.

We made the smallest unit of labor attainable @concurrent to keep away from introducing a great deal of concurrency the place we don’t want it. Introducing concurrency with @concurrent isn’t a nasty factor however we do need to restrict the quantity of concurrency in our app. That’s as a result of concurrency comes with a reasonably excessive complexity value, and fewer complexity in our code sometimes signifies that we write code that’s much less buggy, and simpler to take care of in the long term.

LEAVE A REPLY

Please enter your comment!
Please enter your name here