Classes

class ArrayBlockingQueue<E>

public class ArrayBlockingQueue<E> {
    public let capacity: Int64
    public init(capacity: Int64)
    public init(capacity: Int64, elements: Collection<E>)
}

Description: Implements the Blocking Queue data structure and related operation functions based on arrays.

ArrayBlockingQueue indicates a concurrent queue with a blocking mechanism and requires users to specify the upper limit of capacity.

prop size

public prop size: Int64

Description: Returns the number of elements of an ArrayBlockingQueue instance.

NOTE

This method does not ensure atomicity in concurrency scenarios. This method should be called when no other thread concurrently modifies the ArrayBlockingQueue instance in the environment.

Type: Int64

let capacity

public let capacity: Int64

Description: Obtains the capacity of an ArrayBlockingQueue instance.

Type: Int64

init(Int64)

public init(capacity: Int64)

Description: Constructs an ArrayBlockingQueue instance with a passed capacity.

Parameters:

  • capacity: Int64: initial capacity

Throws:

init(Int64, Collection<E>) (deprecated)

public init(capacity: Int64, elements: Collection<E>)

Description: Constructs an ArrayBlockingQueue instance with a passed capacity and a passed iterator.

NOTE

This method will be deprecated in future releases. The alternative implementation is as follows: Create an empty queue and then add elements specified by elements to the queue.

Parameters:

  • capacity: Int64: initial capacity
  • elements: Collection<E>: initial iterator elements

Throws:

  • IllegalArgumentException: If the value of capacity is less than or equal to 0 or less than the size of elements, this exception is thrown.

func add(E)

public func add(element: E): Unit

Description: Specifies a blocked enqueue operation that, specifically, adds a specified last element of a queue. If the queue is full, the task waits for the queue.

Parameters:

  • element: E: element to be added

Examples:

import std.collection.concurrent.*

main() {
    var blockArr: ArrayBlockingQueue<Int64> = ArrayBlockingQueue<Int64>(2)
    blockArr.add(10)
    println(blockArr.peek())
}

Results:

Some(10)

func add(E, Duration)

public func add(element: E, timeout: Duration): Bool

Description: Specifies a blocked enqueue operation that, specifically, adds a specified last element of a queue, or waits for the time specified by timeout if the queue is full. If timeout is negative, the enqueue operation is performed immediately and the operation result is returned.

Parameters:

  • element: E: element to be added
  • timeout: Duration: waiting time

Returns:

  • Bool: If the element is successfully added, true is returned. If the element is not successfully added within the waiting time, false is returned.

Examples:

import std.collection.concurrent.*
import std.sync.*
import std.time.*

main() {
    let blockArr: ArrayBlockingQueue<Int64> = ArrayBlockingQueue<Int64>(2)

    /* Create a thread, which fills the blocked queue and removes the first element from the blocked queue after sleeping for 1 second. */
    spawn {
        =>
        blockArr.add(0)
        blockArr.add(1)
        sleep(1000 * Duration.millisecond)
        println("New thread moves out of blocked queue head element.")
        blockArr.remove()
    }

    /* The main thread immediately releases the execute permission. After the main thread is woken up, the blocked element is added to the queue. */
    sleep(-1 * Duration.millisecond)
    println("The main thread is woken up.")
    let isSuccess: Bool = blockArr.add(2, 2000 * Duration.millisecond)
    println(isSuccess)
}

Results:

The main thread is woken up.
New thread moves out of blocked queue head element.
true

func dequeue() (deprecated)

public func dequeue(): E

Description: Specifies a blocked dequeue operation that, specifically, obtains the first element of a queue and deletes it.

NOTE

This function will be deprecated in future releases and remove() will be used instead.

Returns:

  • E: first element of the queue

func dequeue(Duration) (deprecated)

public func dequeue(timeout: Duration): Option<E>

Description: Specifies a blocked dequeue operation that, specifically, obtains the first element of a queue and deletes it, or waits for the time specified by timeout if the queue is empty. If timeout is negative, the dequeue operation is performed immediately and the operation result is returned.

NOTE

This function will be deprecated in future releases and remove(Duration) will be used instead.

Parameters:

Returns:

  • Option<E>: first element of the queue. If the first element of the queue is not obtained within the waiting time, None is returned.

func enqueue(E) (deprecated)

public func enqueue(element: E): Unit

Description: Specifies a blocked enqueue operation that, specifically, adds a specified last element of a queue.

NOTE

This function will be deprecated in future releases and add(E) will be used instead.

Parameters:

  • element: E: element to be added

func enqueue(E, Duration) (deprecated)

public func enqueue(element: E, timeout: Duration): Bool

Description: Specifies a blocked enqueue operation that, specifically, adds a specified last element of a queue, or waits for the time specified by timeout if the queue is full. If timeout is negative, the enqueue operation is performed immediately and the operation result is returned.

NOTE

This function will be deprecated in future releases and add(E, Duration) will be used instead.

Parameters:

  • element: E: element to be added
  • timeout: Duration: waiting time

Returns:

  • Bool: If the element is successfully added, true is returned. If the element is not successfully added within the waiting time, false is returned.

func head() (deprecated)

public func head(): Option<E>

Description: Obtains the first element of a queue.

This function is non-blocked.

NOTE

This function will be deprecated in future releases and peek() will be used instead.

Returns:

  • Option<E>: first element of the queue. If the queue is empty, None is returned.

func peek()

public func peek(): Option<E>

Description: Obtains the first element of a queue in non-blocked mode.

Returns:

  • Option<E>: first element of the queue. If the queue is empty, None is returned.

Examples:

import std.collection.concurrent.*

main() {
    let blockArr: ArrayBlockingQueue<Int64> = ArrayBlockingQueue<Int64>(2)
    blockArr.add(2)
    blockArr.add(3)
    println(blockArr.peek())
}

Results:

Some(2)

func remove()

public func remove(): E

Description: Specifies a blocked dequeue operation that, specifically, obtains the first element of a queue and deletes it. If the queue is empty, the task waits for the queue.

Returns:

  • E: first element of the queue

Examples:

import std.collection.concurrent.*

main() {
    let blockArr: ArrayBlockingQueue<Int64> = ArrayBlockingQueue<Int64>(2)
    blockArr.add(2)
    blockArr.add(3)
    println(blockArr.remove())
    println(blockArr.size)
}

Results:

2
1

func remove(Duration)

public func remove(timeout: Duration): Option<E>

Description: Specifies a blocked dequeue operation that, specifically, obtains the first element of a queue and deletes it, or waits for the time specified by timeout if the queue is empty. If timeout is negative, the dequeue operation is performed immediately and the operation result is returned.

Parameters:

Returns:

  • Option<E>: first element of the queue. If the first element of the queue is not obtained within the waiting time, None is returned.

Examples:

import std.collection.concurrent.*
import std.sync.*
import std.time.*

main() {
    let blockArr: ArrayBlockingQueue<Int64> = ArrayBlockingQueue<Int64>(2)

    /* Create a thread, which adds elements to the queue after sleeping for 1 second. */
    spawn {
        =>
        sleep(1000 * Duration.millisecond)
        println("This new thread adds new elements to the queue.")
        blockArr.add(3)
    }

    /* The main thread immediately releases the execute permission. After being woken up, the main thread removes the first element of the queue in blocked mode. */
    sleep(-1 * Duration.millisecond)
    println("The main thread is woken up.")
    let num: Option<Int64> = blockArr.remove(2000 * Duration.millisecond)
    println(num)
}

Results:

The main thread is woken up.
This new thread adds new elements to the queue.
Some(3)

func tryAdd(E)

public func tryAdd(element: E): Bool

Description: Specifies a non-blocked enqueue operation that, specifically, adds a specified last element of a queue.

Parameters:

  • element: E: element to be added

Returns:

  • Bool: If the element is successfully added, true is returned. If the element fails to be added because the queue is full, false is returned.

Examples:

import std.collection.concurrent.*

main() {
    let blockArr: ArrayBlockingQueue<Int64> = ArrayBlockingQueue<Int64>(2)
    blockArr.tryAdd(2)
    blockArr.tryAdd(3)
    println(blockArr.size)
}

Results:

2

func tryDequeue() (deprecated)

public func tryDequeue(): Option<E>

Description: Specifies a non-blocked dequeue operation that, specifically, obtains the first element of a queue and deletes it.

NOTE

This function will be deprecated in future releases and tryRemove() will be used instead.

Returns:

  • Option<E>: first element of the queue. If the queue is empty, None is returned.

func tryEnqueue(E) (deprecated)

public func tryEnqueue(element: E): Bool

Description: Specifies a non-blocked enqueue operation that, specifically, adds a specified last element of a queue.

NOTE

This function will be deprecated in future releases and tryAdd(E) will be used instead.

Parameters:

  • element: E: element to be added

Returns:

  • Bool: If the element is successfully added, true is returned. If the element fails to be added because the queue is full, false is returned.

func tryRemove()

public func tryRemove(): Option<E>

Description: Specifies a non-blocked dequeue operation that, specifically, obtains the first element of a queue and deletes it.

Returns:

  • Option<E>: first element of the queue. If the queue is empty, None is returned.

Examples:

import std.collection.concurrent.*

main() {
    let blockArr: ArrayBlockingQueue<Int64> = ArrayBlockingQueue<Int64>(2)
    blockArr.tryAdd(2)
    println(blockArr.tryRemove())
    println(blockArr.tryRemove())
}

Results:

Some(2)
None

class ConcurrentHashMap<K, V> where K <: Hashable & Equatable<K>

public class ConcurrentHashMap<K, V> <: ConcurrentMap<K, V> & Collection<(K, V)> where K <: Hashable & Equatable<K> {
    public init(concurrencyLevel!: Int64 = 16)
    public init(capacity: Int64, concurrencyLevel!: Int64 = 16)
    public init(elements: Collection<(K, V)>, concurrencyLevel!: Int64 = 16)
    public init(size: Int64, initElement: (Int64) -> (K, V), concurrencyLevel!: Int64 = 16)
}

Description: Implements the data structure and related operation functions of the thread-safe hash table specified by ConcurrentHashMap in concurrency scenarios.

If the number of key-value pairs in a ConcurrentHashMap instance is greater than the number of buckets, capacity is expanded.

The concurrencyLevel parameter in the constructor indicates the concurrency level, that is, the maximum number of threads that are allowed to concurrently modify a ConcurrentHashMap instance. The operation of querying key-value pairs is non-blocked and is not restricted by the specified concurrencyLevel. The default value of concurrencyLevel is 16. It affects only the performance of ConcurrentHashMap in concurrency scenarios and does not affect functions.

NOTE

If the value of concurrencyLevel is less than 16, the concurrency level is set to 16.

A larger concurrencyLevel does not necessarily lead to better performance. A larger concurrencyLevel results in higher memory overhead (or even out-of-memory exceptions). Users need to balance the memory overhead and running efficiency.

Parent types:

Examples:

For details, see ConcurrentHashMap Usage Example.

prop size

public prop size: Int64

Description: Returns the number of key values.

NOTE

This method does not ensure atomicity in concurrency scenarios. This method should be called when no other thread concurrently modifies the ConcurrentHashMap instance in the environment.

Type: Int64

init(Collection<(K, V)>, Int64)

public init(elements: Collection<(K, V)>, concurrencyLevel!: Int64 = 16)

Description: Constructs a ConcurrentHashMap instance with a passed iterator and a specified concurrency level. This constructor sets the capacity of the ConcurrentHashMap instance according to the size of elements.

Parameters:

  • elements: Collection<(K, V)>: initial iterator elements
  • concurrencyLevel!: Int64: specified concurrency level

init(Int64)

public init(concurrencyLevel!: Int64 = 16)

Description: Constructs a ConcurrentHashMap instance with the default initial capacity (16) and a specified concurrency level (16 by default).

Parameters:

  • concurrencyLevel!: Int64: specified concurrency level

init(Int64, (Int64) -> (K, V), Int64)

public init(size: Int64, initElement: (Int64) -> (K, V), concurrencyLevel!: Int64 = 16)

Description: Constructs a ConcurrentHashMap instance with a passed size, initial function elements, and a specified concurrency level. This constructor sets the capacity of the ConcurrentHashMap instance according to the size parameter.

Parameters:

  • size: Int64: initial function element size
  • initElement: (Int64) -> (K, V): initial function elements
  • concurrencyLevel!: Int64: specified concurrency level

Throws:

init(Int64, Int64)

public init(capacity: Int64, concurrencyLevel!: Int64 = 16)

Description: Constructs a ConcurrentHashMap instance with a passed capacity and a specified concurrency level (16 by default).

Parameters:

  • capacity: Int64: initial capacity
  • concurrencyLevel!: Int64: specified concurrency level

Throws:

func add(K, V)

public func add(key: K, value: V): ?V

Description: Associates a specified value with a key specified in a ConcurrentHashMap instance. If the ConcurrentHashMap instance already contains the association of the key, the old value is replaced. If the ConcurrentHashMap instance does not contain the association of the key, the association between the key and the value is added.

Parameters:

  • key: K: key to be put
  • value: V: value to be associated

Returns:

  • ?V: If the key exists before value assignment, the old value Some(V) is returned. If the key does not exist before value assignment, None is returned.

Examples:

import std.collection.concurrent.*

main() {
    let map: ConcurrentHashMap<Int64, Int64> = ConcurrentHashMap<Int64, Int64>(3, {value => (value, value)})
    let oldValue = map.add(2, 3)
    println(oldValue)
    let newValue = map.add(3, 3)
    println(newValue)
    let iter = ConcurrentHashMapIterator<Int64, Int64>(map)
    while (true) {
        match (iter.next()) {
            case Some(i) => println("(${i[0]},${i[1]})")
            case None => break
        }
    }
}

Results:

Some(2)
None
(0,0)
(1,1)
(2,3)
(3,3)

func addIfAbsent(K, V)

public func addIfAbsent(key: K, value: V): ?V

Description: Adds the association between a specified value and a specified key to a ConcurrentHashMap instance if the ConcurrentHashMap instance does not contain the key. If the ConcurrentHashMap instance already contains the key, the value assignment is not performed.

Parameters:

  • key: K: key to be put
  • value: V: value to be assigned

Returns:

  • ?V: If the key exists before value assignment, the value Some(V) corresponding to the current key is returned and the value assignment is not performed. If the key does not exist before value assignment, None is returned.

Examples:

import std.collection.concurrent.*

main() {
    let map: ConcurrentHashMap<Int64, Int64> = ConcurrentHashMap<Int64, Int64>(3, {value => (value, value)})
    let oldValue = map.addIfAbsent(2, 3)
    println(oldValue)
    let newValue = map.addIfAbsent(3, 3)
    println(newValue)
    let iter = ConcurrentHashMapIterator<Int64, Int64>(map)
    while (true) {
        match (iter.next()) {
            case Some(i) => println("(${i[0]},${i[1]})")
            case None => break
        }
    }
}

Results:

Some(2)
None
(0,0)
(1,1)
(2,2)
(3,3)

func contains(K)

public func contains(key: K): Bool

Description: Checks whether a mapping contains the mapping of a specified key.

Parameters:

  • key: K: key to be checked

Returns:

  • Bool: whether the mapping of the specified key is contained. If so, true is returned. If not, false is returned.

Examples:

import std.collection.concurrent.*

main() {
    let map: ConcurrentHashMap<Int64, Int64> = ConcurrentHashMap<Int64, Int64>(3, {value => (value, value)})
    map.add(3, 3)
    println(map.contains(3))
    println(map.contains(6))
}

Results:

true
false

func entryView(K, (MapEntryView<K, V>) -> Unit)

public func entryView(key: K, fn: (MapEntryView<K, V>) -> Unit): ?V

Description: Obtains the entryView of the corresponding key-value pair in the current mapping based on a specified key, calls the fn function to add, delete, or modify the key-value pair, and returns the value corresponding to the key in the final mapping.

If the current mapping does not contain the key, an empty entryView is obtained. In this case, if the value is set to a value other than None, the key-value pair is added to the current mapping.

If the current mapping contains the key, the key-value view is obtained. In this case, if the value is set to None, the key-value pair is deleted from the current mapping; if the value is set to a new value other than None, the value of the key in the current mapping is changed.

Note that the entryView, remove, and replace functions cannot be called concurrently in the fn parameter. For details, see the following example:

map.entryView(1) { _ =>
    let f = spawn {
        map.entryView(17) { _ => () }
    }
    f.get()
}

NOTE

  • This operation is atomic.

  • The modification of the key-value pair during the fn callback is not updated to the current mapping in real time. The modification is updated to the current mapping after the entryView function is called.

Parameters:

  • key: K: key whose view is to be obtained
  • fn: (MapEntryView<K, V>) -> Unit: custom operation on the specified view, which can be used to add, delete, or modify key-value pairs in the mapping

Returns:

  • ?V: value of key in the current mapping after the fn function is called. If the key does not exist, None is returned.

Examples:

import std.collection.concurrent.*

main() {
    let map: ConcurrentHashMap<Int64, Int64> = ConcurrentHashMap<Int64, Int64>(2, {value => (value, value)})
    map.add(2, 2)

    /* If the current mapping does not contain the key-value pair whose key is 3, set entryView.value to 7, which is equivalent to adding the key-value pair (3,7). */
    let num1 = map.entryView(3, {view => view.value = 7})
    println(num1)

    /* If the current mapping contains the key-value pair whose key is 2, set entryView.value to 6, which is equivalent to updating the value of key 1 to 6. */
    let num2 = map.entryView(1, {view => view.value = 6})
    println(num2)

    /* If the current mapping contains the key-value pair whose key is 0, set entryView.value to None, which is equivalent to deleting the key-value pair whose key is 0. */
    let num3 = map.entryView(0, {view => view.value = None})
    println(num3)

    let iter = ConcurrentHashMapIterator<Int64, Int64>(map)
    while (true) {
        match (iter.next()) {
            case Some(i) => println("(${i[0]},${i[1]})")
            case None => break
        }
    }
}

Results:

Some(7)
Some(6)
None
(1,6)
(2,2)
(3,7)

func get(K)

public func get(key: K): ?V

Description: Returns the value associated with a key in a mapping.

Parameters:

  • key: K: key used to obtain a value

Returns:

  • ?V: value associated with the key in the mapping

func isEmpty()

public func isEmpty(): Bool

Description: Checks whether a ConcurrentHashMap instance is empty.

NOTE

This method does not ensure atomicity in concurrency scenarios. This method should be called when no other thread concurrently modifies the ConcurrentHashMap instance in the environment.

Returns:

  • Bool: If the instance is empty, true is returned. Otherwise, false is returned.

func iterator()

public func iterator(): ConcurrentHashMapIterator<K, V>

Description: Obtains the iterator of a ConcurrentHashMap instance.

Returns:

Examples:

import std.collection.concurrent.*

main() {
    let map: ConcurrentHashMap<Int64, Int64> = ConcurrentHashMap<Int64, Int64>(3, {value => (value, value)})
    let iter = map.iterator()
    while (true) {
        match (iter.next()) {
            case Some(i) => println("(${i[0]},${i[1]})")
            case None => break
        }
    }
}

Results:

(0,0)
(1,1)
(2,2)

func put(K, V) (deprecated)

public func put(key: K, value: V): ?V

Description: Associates a specified value with a key specified in a ConcurrentHashMap instance. If the ConcurrentHashMap instance already contains the association of the key, the old value is replaced. If the ConcurrentHashMap instance does not contain the association of the key, the association between the key and the value is added.

NOTE

This function will be deprecated in future releases and add(K, V) will be used instead.

Parameters:

  • key: K: key to be put
  • value: V: value to be associated

Returns:

  • ?V: If the key exists before value assignment, the old value Some(V) is returned. If the key does not exist before value assignment, None is returned.

func putIfAbsent(K, V) (deprecated)

public func putIfAbsent(key: K, value: V): ?V

Description: Adds the association between a specified value and a specified key to a ConcurrentHashMap instance if the ConcurrentHashMap instance does not contain the key. If the ConcurrentHashMap instance already contains the key, the value assignment is not performed.

NOTE

This function will be deprecated in future releases and addIfAbsent(K, V) will be used instead.

Parameters:

  • key: K: key to be put
  • value: V: value to be assigned

Returns:

  • ?V: If the key exists before value assignment, the value Some(V) corresponding to the current key is returned and the value assignment is not performed. If the key does not exist before value assignment, None is returned.

func remove((K, (V) -> Bool)) (deprecated)

public func remove(key: K, predicate: (V) -> Bool): ?V

Description: Deletes the mapping of a key if the key exists in a mapping and the value v mapped to the key meets the condition of predicate.

NOTE

This function will be deprecated in future releases and entryView(K, (MapEntryView<K, V>) -> Unit) will be used instead.

Parameters:

  • key: K: key to be deleted
  • predicate: (V) ->Bool: lambda expression used for judgment

Returns:

  • ?V: If the key exists in the mapping, the old value corresponding to the key is returned. If the key does not exist in the mapping or the value associated with the key does not meet the condition of predicate, None is returned.

func remove(K)

public func remove(key: K): ?V

Description: Deletes the mapping (if any) of a specified key from a mapping.

Parameters:

  • key: K: key to be deleted

Returns:

  • ?V: If the key exists before the deletion, the value Some (V) corresponding to the key is returned. If the key does not exist before the deletion, None is returned.

Examples:

import std.collection.concurrent.*

main() {
    let map: ConcurrentHashMap<Int64, Int64> = ConcurrentHashMap<Int64, Int64>(3, {value => (value, value)})
    let num = map.remove(0)
    println(num)
    let iter = map.iterator()
    while (true) {
        match (iter.next()) {
            case Some(i) => println("(${i[0]},${i[1]})")
            case None => break
        }
    }
}

Results:

Some(0)
(1,1)
(2,2)

func replace(K, (V) -> Bool, (V) -> V) (deprecated)

public func replace(key: K, predicate: (V) -> Bool, eval: (V) -> V): ?V

Description: Replaces the value associated with a key in a ConcurrentHashMap instance with the calculation result of eval(v) if the key (assuming that the value associated with the key is v) exists in the ConcurrentHashMap instance and v meets the condition of predicate. The ConcurrentHashMap instance is not modified if the key does not exist in the ConcurrentHashMap instance or the key exists but the value associated with the key does not meet the condition of predicate.

NOTE

This function will be deprecated in future releases and entryView(K, (MapEntryView<K, V>) -> Unit) will be used instead.

Parameters:

  • key: K: key whose associated value is to be replaced
  • predicate: (V) ->Bool: lambda expression used for judgment
  • eval: (V) ->V: function used to calculate a new value used for replacement

Returns:

  • ?V: If the key exists, the old value Some(V) corresponding to the key is returned. If the key does not exist or the value associated with the key does not meet the condition of predicate, None is returned.

func replace(K, (V) -> V) (deprecated)

public func replace(key: K, eval: (V) -> V): ?V

Description: Replaces the value associated with a key in a ConcurrentHashMap instance with the calculation result of eval(v) if the key (assuming that the value associated with the key is v) exists in the ConcurrentHashMap instance. The ConcurrentHashMap instance is not modified if the key does not exist in the ConcurrentHashMap instance.

NOTE

This function will be deprecated in future releases and entryView(K, (MapEntryView<K, V>) -> Unit) will be used instead.

Parameters:

  • key: K: key whose associated value is to be replaced
  • eval: (V) ->V: function used to calculate a new value used for replacement

Returns:

  • ?V: If the key exists, the old value Some(V) corresponding to the key is returned. If the key does not exist, None is returned.

func replace(K, V)

public func replace(key: K, value: V): ?V

Description: Replaces the value associated with a key in a ConcurrentHashMap instance with the value specified by value if the key exists in the ConcurrentHashMap instance. The ConcurrentHashMap instance is not modified if the key does not exist in the ConcurrentHashMap instance.

Parameters:

  • key: K: key whose associated value is to be replaced
  • value: V: new value used for replacement

Returns:

  • ?V: If the key exists, the old value Some(V) corresponding to the key is returned. If the key does not exist, None is returned.

Examples:

import std.collection.concurrent.*

main() {
    let map: ConcurrentHashMap<Int64, Int64> = ConcurrentHashMap<Int64, Int64>(3, {value => (value, value)})
    let num = map.replace(0, 2)
    println(num)
    let iter = map.iterator()
    while (true) {
        match (iter.next()) {
            case Some(i) => println("(${i[0]},${i[1]})")
            case None => break
        }
    }
}

Results:

Some(0)
(0,2)
(1,1)
(2,2)

operator func [](K)

public operator func [](key: K): V

Description: Overloads the indexing operator. If a key exists, the value corresponding to the key is returned. If a key does not exist, an exception is thrown.

Parameters:

  • key: K: key used for judgment

Returns:

  • V: value corresponding to the key

Throws:

  • NoneValueException: If the key does not exist in associations, this exception is thrown.

operator func [](K, V)

public operator func [](key: K, value!: V): Unit

Description: Overloads the indexing operator. If a key exists, the new value overwrites the old value. If a key does not exist, the key-value pair is added.

Parameters:

  • key: K: key used for judgment
  • value!: V: value to be set

class ConcurrentHashMapIterator<K, V> where K <: Hashable & Equatable<K>

public class ConcurrentHashMapIterator<K, V> <: Iterator<(K, V)> where K <: Hashable & Equatable<K> {
    public init(cmap: ConcurrentHashMap<K, V>)
}

Description: Implements the iterator functionality of ConcurrentHashMap.

NOTE

The ConcurrentHashMap iterator is defined as follows:

  1. The iteration result may not be a snapshot of the concurrent HashMap instance at a certain time point. The iterator should be called when no other thread concurrently modifies the ConcurrentHashMap instance in the environment.
  2. During iteration, the iterator may not be aware of the modification of the target ConcurrentHashMap instance by an environment thread.

Parent types:

init(ConcurrentHashMap<K, V>)

public init(cmap: ConcurrentHashMap<K, V>)

Description: Creates a ConcurrentHashMapIterator<K, V> instance.

Parameters:

func next()

public func next(): Option<(K, V)>

Description: Returns the next element in an iterator.

Returns:

Examples:

import std.collection.concurrent.*

main() {
    let map: ConcurrentHashMap<Int64, Int64> = ConcurrentHashMap<Int64, Int64>(3, {value => (value, value)})
    let iter = ConcurrentHashMapIterator<Int64, Int64>(map)
    while (true) {
        match (iter.next()) {
            case Some(i) => println("(${i[0]},${i[1]})")
            case None => break
        }
    }
}

Results:

(0,0)
(1,1)
(2,2)

class ConcurrentLinkedQueue<E>

public class ConcurrentLinkedQueue<E> <: Collection<E> {
    public init()
    public init(elements: Collection<E>)
}

Description: Provides thread-safe queues to safely add and delete elements in a multi-thread environment.

A purpose of non-blocked queues is to resolve a synchronization problem in a multi-thread environment so that a plurality of threads can concurrently perform queue operations, and no data conflict or deadlock problem occurs.

Non-blocked queues are common in multi-thread programming. They can be used in any scenario where thread-safe queues are required, such as the producer-consumer model, task scheduling, and thread pool.

Parent types:

Examples:

For details, see ConcurrentLinkedQueue Usage Example.

prop size

public prop size: Int64

Description: Obtains the number of elements of a ConcurrentLinkedQueue instance.

NOTE

This method does not ensure atomicity in concurrency scenarios. This method should be called when no other thread concurrently modifies the ConcurrentLinkedQueue instance in the environment.

Type: Int64

init()

public init()

Description: Constructs a default ConcurrentLinkedQueue instance.

init(Collection<E>) (deprecated)

public init(elements: Collection<E>)

Description: Constructs a ConcurrentLinkedQueue instance based on a collection<E> instance.

NOTE

This method will be deprecated in future releases. The alternative implementation is as follows: Create an empty queue and then add elements in the collection instance to the queue.

Parameters:

func add(E)

public func add(element: E): Bool

Description: Specifies a non-blocked enqueue operation that, specifically, adds a specified last element of a queue.

NOTE

This function does not return false.

Parameters:

  • element: E: element to be added

Returns:

  • Bool: If the element is successfully added, true is returned.

func dequeue() (deprecated)

public func dequeue(): Option<E>

Description: Obtains and deletes the first element of a queue.

NOTE

This function will be deprecated in future releases and remove() will be used instead.

Returns:

  • Option<E>: If the first element is deleted successfully, it is returned. If the queue is empty, None is returned.

func enqueue(E) (deprecated)

public func enqueue(element: E): Bool

Description: Specifies a non-blocked enqueue operation that, specifically, adds a specified last element of a queue.

NOTE

  • This function does not return false.
  • This function will be deprecated in future releases and add(E) will be used instead.

Parameters:

  • element: E: element to be added

Returns:

  • Bool: If the element is successfully added, true is returned.

func head() (deprecated)

public func head(): Option<E>

Description: Obtains the first element of a queue without deleting it.

NOTE

This function will be deprecated in future releases and peek() will be used instead.

Returns:

  • Option<E>: If the first element is obtained successfully, it is returned. If the queue is empty, None is returned.

func isEmpty()

public func isEmpty(): Bool

Description: Checks whether the current queue is empty.

Returns:

  • Bool: If the current queue is empty, true is returned. Otherwise, false is returned.

func iterator()

public func iterator(): Iterator<E>

Description: Obtains the iterator of the current queue, which is used to traverse the current queue.

NOTE

The traversal operation does not delete elements from the queue. The traversal operation does not ensure atomicity. If another thread concurrently modifies the current queue, the element obtained through traversal may not be a static slice of the current queue at a moment.

Returns:

  • Iterator<E>: iterator of the current queue

func peek()

public func peek(): Option<E>

Description: Obtains the first element of a queue without deleting it.

Returns:

  • Option<E>: If the first element is obtained successfully, it is returned. If the queue is empty, None is returned.

func remove()

public func remove(): Option<E>

Description: Obtains and deletes the first element of a queue.

Returns:

  • Option<E>: If the first element is deleted successfully, it is returned. If the queue is empty, None is returned.

func toArray()

public func toArray(): Array<E>

Description: Saves all elements in the current queue to an array in sequence. An element that enters the queue earlier is in a position with a smaller array index.

NOTE

This operation does not delete elements from the queue. This operation does not ensure atomicity. If another thread concurrently modifies the current queue, the array obtained through this operation may not be a static slice of the current queue at a moment.

Returns:

  • Array<E>: array obtained, in which the elements are those in the current queue

class LinkedBlockingQueue<E>

public class LinkedBlockingQueue<E> {
    public let capacity: Int64
    public init()
    public init(capacity: Int64)
    public init(capacity: Int64, elements: Array<E>)
    public init(capacity: Int64, elements: Collection<E>)
}

Description: Implements a concurrent queue with a blocking mechanism, which supports users to specify the upper limit of capacity.

A feature of a blocked queue is that when the queue is full, a thread that attempts to add an element to the queue is blocked until there is a vacant position in the queue; and when the queue is empty, a thread that attempts to obtain an element from the queue is blocked until there is an available element in the queue.

let capacity

public let capacity: Int64

Description: Returns the capacity of a LinkedBlockingQueue instance.

Type: Int64

prop size

public prop size: Int64

Description: Returns the number of elements of a LinkedBlockingQueue instance.

NOTE

This method does not ensure atomicity in concurrency scenarios. This method should be called when no other thread concurrently modifies the LinkedBlockingQueue instance in the environment.

Type: Int64

init()

public init()

Description: Constructs a LinkedBlockingQueue instance with the default initial capacity (Int64.Max).

init(Int64)

public init(capacity: Int64)

Description: Constructs a LinkedBlockingQueue instance with a passed capacity.

Parameters:

  • capacity: Int64: initial capacity

Throws:

init(Int64, Array<E>) (deprecated)

public init(capacity: Int64, elements: Array<E>)

Description: Constructs a LinkedBlockingQueue instance with a passed capacity and an array of elements passed.

NOTE

This method will be deprecated in future releases. The alternative implementation is as follows: Create an empty queue and then add elements in the array to the queue.

Parameters:

  • capacity: Int64: initial capacity
  • elements: Array<E>: initial array of elements

Throws:

  • IllegalArgumentException: If the value of capacity is less than or equal to 0 or less than the size of elements, this exception is thrown.

init(Int64, Collection<E>) (deprecated)

public init(capacity: Int64, elements: Collection<E>)

Description: Constructs a LinkedBlockingQueue instance with a passed capacity and a passed iterator.

NOTE

This method will be deprecated in future releases. The alternative implementation is as follows: Create an empty queue and then add elements in the collection instance to the queue.

Parameters:

  • capacity: Int64: initial capacity
  • elements: Collection<E>: initial iterator elements

Throws:

  • IllegalArgumentException: If the value of capacity is less than or equal to 0 or less than the size of elements, this exception is thrown.

func add(E)

public func add(element: E): Unit

Description: Specifies a blocked enqueue operation that, specifically, adds a specified last element of a queue. If the queue is full, the task waits for the queue.

Parameters:

  • element: E: element to be added

Examples:

import std.collection.concurrent.*

main() {
    var blockArr: LinkedBlockingQueue<Int64> = LinkedBlockingQueue<Int64>(2)
    blockArr.add(10)
    println(blockArr.peek())
}

Results:

Some(10)

func add(E, Duration)

public func add(element: E, timeout: Duration): Bool

Description: Specifies a blocked enqueue operation that, specifically, adds a specified last element of a queue, or waits for the time specified by timeout if the queue is full. If timeout is negative, the enqueue operation is performed immediately and the operation result is returned.

Parameters:

  • element: E: element to be added
  • timeout: Duration: waiting time

Returns:

  • Bool: If the element is successfully added, true is returned. If the element is not successfully added within the waiting time, false is returned.

Examples:

import std.collection.concurrent.*
import std.sync.*
import std.time.*

main() {
    let blockArr: LinkedBlockingQueue<Int64> = LinkedBlockingQueue<Int64>(2)

    /* Create a thread, which fills the blocked queue and removes the first element from the blocked queue after sleeping for 1 second. */
    spawn {
        =>
        blockArr.add(0)
        blockArr.add(1)
        sleep(1000 * Duration.millisecond)
        println("New thread moves out of blocked queue head element.")
        blockArr.remove()
    }

    /* The main thread immediately releases the execute permission. After the main thread is woken up, the blocked element is added to the queue. */
    sleep(-1 * Duration.millisecond)
    println("The main thread is woken up.")
    let isSuccess: Bool = blockArr.add(2, 2000 * Duration.millisecond)
    println(isSuccess)
}

Results:

The main thread is woken up.
New thread moves out of blocked queue head element.
true

func dequeue() (deprecated)

public func dequeue(): E

Description: Specifies a blocked dequeue operation that, specifically, obtains the first element of a queue and deletes it.

NOTE

This function will be deprecated in future releases and remove() will be used instead.

Returns:

  • E: first element of the queue

func dequeue(Duration) (deprecated)

public func dequeue(timeout: Duration): Option<E>

Description: Specifies a blocked dequeue operation that, specifically, obtains the first element of a queue and deletes it, or waits for the time specified by timeout if the queue is empty. If timeout is negative, the dequeue operation is performed immediately and the operation result is returned.

NOTE

This function will be deprecated in future releases and remove(Duration) will be used instead.

Parameters:

Returns:

  • Option<E>: first element of the queue. If the first element of the queue is not obtained within the waiting time, None is returned.

func enqueue(E) (deprecated)

public func enqueue(element: E): Unit

Description: Specifies a blocked enqueue operation that, specifically, adds a specified last element of a queue.

NOTE

This function will be deprecated in future releases and add(E) will be used instead.

Parameters:

  • element: E: element to be added

func enqueue(E, Duration) (deprecated)

public func enqueue(element: E, timeout: Duration): Bool

Description: Specifies a blocked enqueue operation that, specifically, adds a specified last element of a queue, or waits for the time specified by timeout if the queue is full. If timeout is negative, the enqueue operation is performed immediately and the operation result is returned.

NOTE

This function will be deprecated in future releases and add(E, Duration) will be used instead.

Parameters:

  • element: E: element to be added
  • timeout: Duration: waiting time

Returns:

  • Bool: If the element is successfully added, true is returned. If the element is not successfully added within the waiting time, false is returned.

func head() (deprecated)

public func head(): Option<E>

Description: Obtains the first element of a queue.

NOTE

  • This function is non-blocked.
  • This function will be deprecated in future releases and peek() will be used instead.

Returns:

  • Option<E>: first element of the queue. If the queue is empty, None is returned.

func peek()

public func peek(): Option<E>

Description: Obtains the first element of a queue.

NOTE

This function is non-blocked.

Returns:

  • Option<E>: first element of the queue. If the queue is empty, None is returned.

Examples:

import std.collection.concurrent.*

main() {
    let blockArr: LinkedBlockingQueue<Int64> = LinkedBlockingQueue<Int64>(2)
    blockArr.add(2)
    blockArr.add(3)
    println(blockArr.peek())
}

Results:

Some(2)

func remove()

public func remove(): E

Description: Specifies a blocked dequeue operation that, specifically, obtains the first element of a queue and deletes it.

Returns:

  • E: first element of the queue

Examples:

import std.collection.concurrent.*

main() {
    let blockArr: LinkedBlockingQueue<Int64> = LinkedBlockingQueue<Int64>(2)
    blockArr.add(2)
    blockArr.add(3)
    println(blockArr.remove())
    println(blockArr.size)
}

Results:

2
1

func remove(Duration)

public func remove(timeout: Duration): Option<E>

Description: Specifies a blocked dequeue operation that, specifically, obtains the first element of a queue and deletes it, or waits for the time specified by timeout if the queue is empty. If timeout is negative, the dequeue operation is performed immediately and the operation result is returned.

Parameters:

Returns:

  • Option<E>: first element of the queue. If the first element of the queue is not obtained within the waiting time, None is returned.

Examples:

import std.collection.concurrent.*
import std.sync.*
import std.time.*

main() {
    let blockArr: LinkedBlockingQueue<Int64> = LinkedBlockingQueue<Int64>(2)

    /* Create a thread, which adds elements to the queue after sleeping for 1 second. */
    spawn {
        =>
        sleep(1000 * Duration.millisecond)
        println("This new thread adds new elements to the queue.")
        blockArr.add(3)
    }

    /* The main thread immediately releases the execute permission. After being woken up, the main thread removes the first element of the queue in blocked mode. */
    sleep(-1 * Duration.millisecond)
    println("The main thread is woken up.")
    let num: Option<Int64> = blockArr.remove(2000 * Duration.millisecond)
    println(num)
}

Results:

The main thread is woken up.
This new thread adds new elements to the queue.
Some(3)

func tryAdd(E)

public func tryAdd(element: E): Bool

Description: Specifies a non-blocked enqueue operation that, specifically, adds a specified last element of a queue.

Parameters:

  • element: E: element to be added

Returns:

  • Bool: If the element is successfully added, true is returned. If the element fails to be added because the queue is full, false is returned.

Examples:

import std.collection.concurrent.*

main() {
    let blockArr: LinkedBlockingQueue<Int64> = LinkedBlockingQueue<Int64>(2)
    blockArr.tryAdd(2)
    blockArr.tryAdd(3)
    println(blockArr.size)
}

Results:

2

func tryDequeue() (deprecated)

public func tryDequeue(): Option<E>

Description: Specifies a non-blocked dequeue operation that, specifically, obtains the first element of a queue and deletes it.

NOTE

This function will be deprecated in future releases and tryRemove() will be used instead.

Returns:

  • Option<E>: first element of the queue. If the queue is empty, None is returned.

func tryEnqueue(E) (deprecated)

public func tryEnqueue(element: E): Bool

Description: Specifies a non-blocked enqueue operation that, specifically, adds a specified last element of a queue.

NOTE

This function will be deprecated in future releases and tryAdd(E) will be used instead.

Parameters:

  • element: E: element to be added

Returns:

  • Bool: If the element is successfully added, true is returned. If the element fails to be added because the queue is full, false is returned.

func tryRemove()

public func tryRemove(): Option<E>

Description: Specifies a non-blocked dequeue operation that, specifically, obtains the first element of a queue and deletes it.

Returns:

  • Option<E>: first element of the queue. If the queue is empty, None is returned.

Examples:

import std.collection.concurrent.*

main() {
    let blockArr: LinkedBlockingQueue<Int64> = LinkedBlockingQueue<Int64>(2)
    blockArr.tryAdd(3)
    println(blockArr.tryRemove())
    println(blockArr.tryRemove())
}

Results:

Some(3)
None