# Module: Concurrent

Defined in:
  lib/concurrent.rb,
  lib/concurrent/map.rb,
  lib/concurrent/set.rb,
  lib/concurrent/atom.rb,
  lib/concurrent/hash.rb,
  lib/concurrent/ivar.rb,
  lib/concurrent/mvar.rb,
  lib/concurrent/tvar.rb,
  lib/concurrent/agent.rb,
  lib/concurrent/array.rb,
  lib/concurrent/async.rb,
  lib/concurrent/delay.rb,
  lib/concurrent/maybe.rb,
  lib/concurrent/tuple.rb,
  lib/concurrent/errors.rb,
  lib/concurrent/future.rb,
  lib/concurrent/options.rb,
  lib/concurrent/promise.rb,
  lib/concurrent/version.rb,
  lib/concurrent/dataflow.rb,
  lib/concurrent/promises.rb,
  lib/concurrent/constants.rb,
  lib/concurrent/exchanger.rb,
  lib/concurrent/re_include.rb,
  lib/concurrent/timer_task.rb,
  lib/concurrent/atomic/event.rb,
  lib/concurrent/configuration.rb,
  lib/concurrent/mutable_struct.rb,
  lib/concurrent/scheduled_task.rb,
  lib/concurrent/utility/engine.rb,
  lib/concurrent/concern/logging.rb,
  lib/concurrent/settable_struct.rb,
  lib/concurrent/synchronization.rb,
  lib/concurrent/utility/at_exit.rb,
  lib/concurrent/atomic/semaphore.rb,
  lib/concurrent/immutable_struct.rb,
  lib/concurrent/thread_safe/util.rb,
  lib/concurrent/concern/obligation.rb,
  lib/concurrent/concern/observable.rb,
  lib/concurrent/executor/timer_set.rb,
  lib/concurrent/concern/deprecation.rb,
  lib/concurrent/atomic/atomic_fixnum.rb,
  lib/concurrent/synchronization/lock.rb,
  lib/concurrent/atomic/atomic_boolean.rb,
  lib/concurrent/atomic/cyclic_barrier.rb,
  lib/concurrent/atomic/mutex_semaphore.rb,
  lib/concurrent/atomic/read_write_lock.rb,
  lib/concurrent/synchronization/object.rb,
  lib/concurrent/thread_safe/util/adder.rb,
  lib/concurrent/utility/monotonic_time.rb,
  lib/concurrent/utility/native_integer.rb,
  lib/concurrent/atomic/atomic_reference.rb,
  lib/concurrent/atomic/count_down_latch.rb,
  lib/concurrent/atomic/thread_local_var.rb,
  lib/concurrent/concern/dereferenceable.rb,
  lib/concurrent/synchronization/volatile.rb,
  lib/concurrent/executor/executor_service.rb,
  lib/concurrent/synchronization/condition.rb,
  lib/concurrent/thread_safe/util/volatile.rb,
  lib/concurrent/utility/processor_counter.rb,
  lib/concurrent/atomic/mutex_atomic_fixnum.rb,
  lib/concurrent/collection/lock_free_stack.rb,
  lib/concurrent/executor/fixed_thread_pool.rb,
  lib/concurrent/synchronization/mri_object.rb,
  lib/concurrent/synchronization/rbx_object.rb,
  lib/concurrent/thread_safe/util/striped64.rb,
  lib/concurrent/atomic/mutex_atomic_boolean.rb,
  lib/concurrent/executor/cached_thread_pool.rb,
  lib/concurrent/executor/immediate_executor.rb,
  lib/concurrent/executor/safe_task_executor.rb,
  lib/concurrent/atomic/java_count_down_latch.rb,
  lib/concurrent/atomic/java_thread_local_var.rb,
  lib/concurrent/atomic/ruby_thread_local_var.rb,
  lib/concurrent/synchronization/jruby_object.rb,
  lib/concurrent/atomic/mutex_count_down_latch.rb,
  lib/concurrent/atomic_reference/mutex_atomic.rb,
  lib/concurrent/executor/serialized_execution.rb,
  lib/concurrent/executor/thread_pool_executor.rb,
  lib/concurrent/collection/map/mri_map_backend.rb,
  lib/concurrent/executor/java_executor_service.rb,
  lib/concurrent/executor/ruby_executor_service.rb,
  lib/concurrent/executor/single_thread_executor.rb,
  lib/concurrent/synchronization/abstract_object.rb,
  lib/concurrent/synchronization/abstract_struct.rb,
  lib/concurrent/synchronization/lockable_object.rb,
  lib/concurrent/thread_safe/util/cheap_lockable.rb,
  lib/concurrent/utility/native_extension_loader.rb,
  lib/concurrent/atomic/abstract_thread_local_var.rb,
  lib/concurrent/atomic/atomic_markable_reference.rb,
  lib/concurrent/atomic/reentrant_read_write_lock.rb,
  lib/concurrent/executor/serial_executor_service.rb,
  lib/concurrent/executor/simple_executor_service.rb,
  lib/concurrent/thread_safe/util/data_structures.rb,
  lib/concurrent/thread_safe/util/xor_shift_random.rb,
  lib/concurrent/executor/abstract_executor_service.rb,
  lib/concurrent/executor/java_thread_pool_executor.rb,
  lib/concurrent/executor/ruby_thread_pool_executor.rb,
  lib/concurrent/synchronization/truffleruby_object.rb,
  lib/concurrent/thread_safe/synchronized_delegator.rb,
  lib/concurrent/synchronization/rbx_lockable_object.rb,
  lib/concurrent/thread_safe/util/power_of_two_tuple.rb,
  lib/concurrent/atomic_reference/numeric_cas_wrapper.rb,
  lib/concurrent/executor/indirect_immediate_executor.rb,
  lib/concurrent/executor/java_single_thread_executor.rb,
  lib/concurrent/executor/ruby_single_thread_executor.rb,
  lib/concurrent/collection/copy_on_write_observer_set.rb,
  lib/concurrent/synchronization/jruby_lockable_object.rb,
  lib/concurrent/synchronization/mutex_lockable_object.rb,
  lib/concurrent/collection/copy_on_notify_observer_set.rb,
  lib/concurrent/collection/map/synchronized_map_backend.rb,
  lib/concurrent/executor/serialized_execution_delegator.rb,
  lib/concurrent/collection/non_concurrent_priority_queue.rb,
  lib/concurrent/synchronization/abstract_lockable_object.rb,
  lib/concurrent/collection/map/non_concurrent_map_backend.rb,
  lib/concurrent/collection/map/atomic_reference_map_backend.rb,
  lib/concurrent/collection/java_non_concurrent_priority_queue.rb,
  lib/concurrent/collection/ruby_non_concurrent_priority_queue.rb,
  lib-edge/concurrent/edge.rb,
  lib-edge/concurrent/actor.rb,
  lib-edge/concurrent/channel.rb,
  lib-edge/concurrent/actor/core.rb,
  lib-edge/concurrent/actor/root.rb,
  lib-edge/concurrent/actor/utils.rb,
  lib-edge/concurrent/actor/errors.rb,
  lib-edge/concurrent/channel/tick.rb,
  lib-edge/concurrent/actor/context.rb,
  lib-edge/concurrent/edge/promises.rb,
  lib-edge/concurrent/edge/throttle.rb,
  lib-edge/concurrent/lazy_register.rb,
  lib-edge/concurrent/actor/envelope.rb,
  lib-edge/concurrent/actor/behaviour.rb,
  lib-edge/concurrent/actor/reference.rb,
  lib-edge/concurrent/actor/type_check.rb,
  lib-edge/concurrent/actor/utils/pool.rb,
  lib-edge/concurrent/channel/selector.rb,
  lib-edge/concurrent/edge/cancellation.rb,
  lib-edge/concurrent/actor/utils/ad_hoc.rb,
  lib-edge/concurrent/channel/buffer/base.rb,
  lib-edge/concurrent/actor/utils/balancer.rb,
  lib-edge/concurrent/channel/buffer/timer.rb,
  lib-edge/concurrent/edge/lock_free_queue.rb,
  lib-edge/concurrent/actor/utils/broadcast.rb,
  lib-edge/concurrent/channel/buffer/ticker.rb,
  lib-edge/concurrent/edge/processing_actor.rb,
  lib-edge/concurrent/actor/behaviour/awaits.rb,
  lib-edge/concurrent/actor/behaviour/buffer.rb,
  lib-edge/concurrent/channel/buffer/sliding.rb,
  lib-edge/concurrent/actor/behaviour/linking.rb,
  lib-edge/concurrent/actor/behaviour/pausing.rb,
  lib-edge/concurrent/channel/buffer/buffered.rb,
  lib-edge/concurrent/channel/buffer/dropping.rb,
  lib-edge/concurrent/actor/behaviour/abstract.rb,
  lib-edge/concurrent/actor/public_delegations.rb,
  lib-edge/concurrent/channel/buffer/unbuffered.rb,
  lib-edge/concurrent/edge/lock_free_linked_set.rb,
  lib-edge/concurrent/actor/internal_delegations.rb,
  lib-edge/concurrent/actor/behaviour/supervising.rb,
  lib-edge/concurrent/actor/behaviour/termination.rb,
  lib-edge/concurrent/channel/selector/put_clause.rb,
  lib-edge/concurrent/actor/behaviour/sets_results.rb,
  lib-edge/concurrent/channel/selector/take_clause.rb,
  lib-edge/concurrent/edge/old_channel_integration.rb,
  lib-edge/concurrent/actor/behaviour/removes_child.rb,
  lib-edge/concurrent/channel/selector/after_clause.rb,
  lib-edge/concurrent/channel/selector/error_clause.rb,
  lib-edge/concurrent/edge/lock_free_linked_set/node.rb,
  lib-edge/concurrent/channel/selector/default_clause.rb,
  lib-edge/concurrent/actor/behaviour/executes_context.rb,
  lib-edge/concurrent/edge/lock_free_linked_set/window.rb,
  lib-edge/concurrent/actor/default_dead_letter_handler.rb,
  lib-edge/concurrent/actor/behaviour/errors_on_unknown_message.rb

## Overview

# Concurrent Ruby

Modern concurrency tools for Ruby. Inspired by Erlang, Clojure, Scala, Haskell, F#, C#, Java, and classic concurrency patterns.

The design goals of this gem are:

- Be an 'unopinionated' toolbox that provides useful utilities without debating which is better or why
- Remain free of external gem dependencies
- Stay true to the spirit of the languages providing inspiration
- But implement in a way that makes sense for Ruby
- Keep the semantics as idiomatic Ruby as possible
- Support features that make sense in Ruby
- Exclude features that don't make sense in Ruby
- Be small, lean, and loosely coupled
- Thread-safety
- Backward compatibility

## Contributing

This gem depends on contributions and we appreciate your help. Would you like to contribute? Great! Have a look at issues with `looking-for-contributor` label. And if you pick something up let us know on the issue.

## Thread Safety

Concurrent Ruby makes one of the strongest thread safety guarantees of any Ruby concurrency library, providing consistent behavior and guarantees on all three of the main Ruby interpreters (MRI/CRuby, JRuby, Rubinius, TruffleRuby).

Every abstraction in this library is thread safe. Specific thread safety guarantees are documented with each abstraction.

It is critical to remember, however, that Ruby is a language of mutable references. No concurrency library for Ruby can ever prevent the user from making thread safety mistakes (such as sharing a mutable object between threads and modifying it on both threads) or from creating deadlocks through incorrect use of locks. All the library can do is provide safe abstractions which encourage safe practices. Concurrent Ruby provides more safe concurrency abstractions than any other Ruby library, many of which support the mantra of "Do not communicate by sharing memory; instead, share memory by communicating". Concurrent Ruby is also the only Ruby library which provides a full suite of thread safe and immutable variable types and data structures.

We've also initiated discussion to document memory model of Ruby which would provide consistent behaviour and guarantees on all four of the main Ruby interpreters (MRI/CRuby, JRuby, Rubinius, TruffleRuby).

## Features & Documentation

The primary site for documentation is the automatically generated API documentation which is up to date with latest release. This readme matches the master so may contain new stuff not yet released.

We also have a IRC (gitter).

### Versioning

- `concurrent-ruby` uses Semantic Versioning
- `concurrent-ruby-ext` has always same version as `concurrent-ruby`
- `concurrent-ruby-edge` will always be 0.y.z therefore following point 4 applies "Major version zero (0.y.z) is for initial development. Anything may change at any time. The public API should not be considered stable." However we additionally use following rules:
  - Minor version increment means incompatible changes were made
  - Patch version increment means only compatible changes were made

#### General-purpose Concurrency Abstractions

- Async: A mixin module that provides simple asynchronous behavior to a class. Loosely based on Erlang's gen_server.
- ScheduledTask: Like a Future scheduled for a specific future time.
- TimerTask: A Thread that periodically wakes up to perform work at regular intervals.
- Promises: Unified implementation of futures and promises which combines features of previous `Future`, `Promise`, `IVar`, `Event`, `dataflow`, `Delay`, and (partially) `TimerTask` into a single framework. It extensively uses the new synchronization layer to make all the features non-blocking and lock-free, with the exception of obviously blocking operations like `#wait`, `#value`. It also offers better performance.

#### Thread-safe Value Objects, Structures, and Collections

Collection classes that were originally part of the (deprecated) `thread_safe` gem:

- Array A thread-safe subclass of Ruby's standard Array.
- Hash A thread-safe subclass of Ruby's standard Hash.
- Set A thread-safe subclass of Ruby's standard Set.
- Map A hash-like object that should have much better performance characteristics, especially under high concurrency, than `Concurrent::Hash`.
- Tuple A fixed size array with volatile (synchronized, thread safe) getters/setters.

Value objects inspired by other languages:

- Maybe A thread-safe, immutable object representing an optional value, based on Haskell Data.Maybe.

Structure classes derived from Ruby's Struct:

- ImmutableStruct Immutable struct where values are set at construction and cannot be changed later.
- MutableStruct Synchronized, mutable struct where values can be safely changed at any time.
- SettableStruct Synchronized, write-once struct where values can be set at most once, either at construction or any time thereafter.

Thread-safe variables:

- Agent: A way to manage shared, mutable, asynchronous, independent state. Based on Clojure's Agent.
- Atom: A way to manage shared, mutable, synchronous, independent state. Based on Clojure's Atom.
- AtomicBoolean A boolean value that can be updated atomically.
- AtomicFixnum A numeric value that can be updated atomically.
- AtomicReference An object reference that may be updated atomically.
- Exchanger A synchronization point at which threads can pair and swap elements within pairs. Based on Java's Exchanger.
- MVar A synchronized single element container. Based on Haskell's MVar and Scala's MVar.
- ThreadLocalVar A variable where the value is different for each thread.
- TVar A transactional variable implementing software transactional memory (STM). Based on Clojure's Ref.

#### Java-inspired ThreadPools and Other Executors

- See the thread pool overview, which also contains a list of other Executors available.

#### Thread Synchronization Classes and Algorithms

- CountDownLatch A synchronization object that allows one thread to wait on multiple other threads.
- CyclicBarrier A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point.
- Event Old school kernel-style event.
- ReadWriteLock A lock that supports multiple readers but only one writer.
- ReentrantReadWriteLock A read/write lock with reentrant and upgrade features.
- Semaphore A counting-based locking mechanism that uses permits.
- AtomicMarkableReference

#### Deprecated

Deprecated features are still available and bugs are being fixed, but new features will not be added.

- Future: An asynchronous operation that produces a value. Replaced by Promises.
  - .dataflow: Built on Futures, Dataflow allows you to create a task that will be scheduled when all of its data dependencies are available. Replaced by Promises.
- Promise: Similar to Futures, with more features. Replaced by Promises.
- Delay Lazy evaluation of a block yielding an immutable result. Based on Clojure's delay. Replaced by Promises.
- IVar Similar to a "future" but can be manually assigned once, after which it becomes immutable. Replaced by Promises.

### Edge Features

These are available in the `concurrent-ruby-edge` companion gem.

These features are under active development and may change frequently. They are expected not to keep backward compatibility (there may also lack tests and documentation). Semantic versions will be obeyed though. Features developed in `concurrent-ruby-edge` are expected to move to `concurrent-ruby` when final.

- Actor: Implements the Actor Model, where concurrent actors exchange messages. Status: Partial documentation and tests; depends on new future/promise framework; stability is good.
- Channel: Communicating Sequential Processes (CSP). Functionally equivalent to Go channels with additional inspiration from Clojure core.async. Status: Partial documentation and tests.
- LazyRegister
- LockFreeLinkedSet Status: will be moved to core soon.
- LockFreeStack Status: missing documentation and tests.

## Supported Ruby versions

- MRI 2.0 and above
- JRuby 9000
- TruffleRuby are supported.
- Any Ruby interpreter that is compliant with Ruby 2.0 or newer.

Actually we still support mri 1.9.3 and jruby 1.7.27 but we are looking at ways how to drop the support. Java 8 is preferred for JRuby but every Java version on which JRuby 9000 runs is supported.

The legacy support for Rubinius is kept but it is no longer maintained, if you would like to help please respond to #739.

## Usage

Everything within this gem can be loaded simply by requiring it:

    require 'concurrent'

Requiring only specific abstractions from Concurrent Ruby is not yet supported.

To use the tools in the Edge gem it must be required separately:

    require 'concurrent-edge'

If the library does not behave as expected, `Concurrent.use_stdlib_logger(Logger::DEBUG)` could help to reveal the problem.

## Installation

    gem install concurrent-ruby

or add the following line to Gemfile:

    gem 'concurrent-ruby', require: 'concurrent'

and run `bundle install` from your shell.

### Edge Gem Installation

The Edge gem must be installed separately from the core gem:

    gem install concurrent-ruby-edge

or add the following line to Gemfile:

    gem 'concurrent-ruby-edge', require: 'concurrent-edge'

and run `bundle install` from your shell.

### C Extensions for MRI

Potential performance improvements may be achieved under MRI by installing optional C extensions. To minimise installation errors the C extensions are available in the `concurrent-ruby-ext` extension gem. `concurrent-ruby` and `concurrent-ruby-ext` are always released together with same version. Simply install the extension gem too:

    gem install concurrent-ruby-ext

or add the following line to Gemfile:

    gem 'concurrent-ruby-ext'

and run `bundle install` from your shell.

In code it is only necessary to

    require 'concurrent'

The `concurrent-ruby` gem will automatically detect the presence of the `concurrent-ruby-ext` gem and load the appropriate C extensions.

#### Note For gem developers

No gems should depend on `concurrent-ruby-ext`. Doing so will force C extensions on your users. The best practice is to depend on `concurrent-ruby` and let users to decide if they want C extensions.

## Maintainers

- Petr Chalupa (lead maintainer, point-of-contact)
- Jerry D'Antonio (creator)
- Chris Seaton

### Special Thanks to

- Brian Durand for the `ref` gem
- Charles Oliver Nutter for the `atomic` and `thread_safe` gems
- thedarkone for the `thread_safe` gem

and to the past maintainers

- Michele Della Torre
- Paweł Obrok
- Lucas Allan

## License and Copyright

Concurrent Ruby is free software released under the MIT License.

The Concurrent Ruby logo was designed by David Jones. It is Copyright © 2014 Jerry D'Antonio. All Rights Reserved.

## Defined Under Namespace

Modules: Actor, Async, Concern, Edge, ImmutableStruct, MutableStruct, Promises, ReInclude, SettableStruct, Synchronization, Utility Classes: Agent, Array, Atom, AtomicBoolean, AtomicFixnum, AtomicMarkableReference, AtomicReference, CachedThreadPool, Cancellation, Channel, ConcurrentUpdateError, CountDownLatch, CyclicBarrier, Delay, Event, Exchanger, FixedThreadPool, Future, Hash, IVar, ImmediateExecutor, IndirectImmediateExecutor, LazyRegister, LockFreeStack, MVar, Map, Maybe, MultipleAssignmentError, MultipleErrors, ProcessingActor, Promise, ReadWriteLock, ReentrantReadWriteLock, SafeTaskExecutor, ScheduledTask, Semaphore, SerializedExecution, SerializedExecutionDelegator, Set, SimpleExecutorService, SingleThreadExecutor, TVar, ThreadLocalVar, ThreadPoolExecutor, Throttle, TimerSet, TimerTask, Transaction, Tuple

## Constant Summary collapse

Error =

      Class.new(StandardError)

ConfigurationError =

Raised when errors occur during configuration.

      Class.new(Error)

CancelledOperationError =

Raised when an asynchronous operation is cancelled before execution.

      Class.new(Error)

LifecycleError =

Raised when a lifecycle method (such as `stop`) is called in an improper sequence or when the object is in an inappropriate state.

      Class.new(Error)

ImmutabilityError =

Raised when an attempt is made to violate an immutability guarantee.

      Class.new(Error)

IllegalOperationError =

Raised when an operation is attempted which is not legal given the receiver's current state

      Class.new(Error)

InitializationError =

Raised when an object's methods are called when it has not been properly initialized.

      Class.new(Error)

MaxRestartFrequencyError =

Raised when an object with a start/stop lifecycle has been started an excessive number of times. Often used in conjunction with a restart policy or strategy.

      Class.new(Error)

RejectedExecutionError =

Raised by an `Executor` when it is unable to process a given task, possibly because of a reject policy or other internal error.

      Class.new(Error)

ResourceLimitError =

Raised when any finite resource, such as a lock counter, exceeds its maximum limit/threshold.

      Class.new(Error)

TimeoutError =

Raised when an operation times out.

      Class.new(Error)

PromiseExecutionError =

      Class.new(StandardError)

VERSION =

      '1.1.4'

EDGE_VERSION =

      '0.4.1'

NULL_LOGGER =

Suppresses all output when used for logging.

      lambda { |level, progname, message = nil, &block| }

## Class Method Summary collapse

- .abort_transaction ⇒ undocumented

  Abort a currently running transaction - see `Concurrent::atomically`.

- .atomically ⇒ undocumented

  Run a block that reads and writes `TVar`s as a single atomic transaction.

- .call_dataflow(method, executor, *inputs, &block) ⇒ undocumented
- .create_simple_logger(level = Logger::FATAL, output = $stderr) ⇒ Logger

  Logger with provided level and output.

- .create_stdlib_logger(level = Logger::FATAL, output = $stderr) ⇒ Logger deprecated Deprecated.
- .dataflow(*inputs) {|inputs| ... } ⇒ Object

  Dataflow allows you to create a task that will be scheduled when all of its data dependencies are available.

- .dataflow!(*inputs, &block) ⇒ undocumented
- .dataflow_with(executor, *inputs, &block) ⇒ undocumented
- .dataflow_with!(executor, *inputs, &block) ⇒ undocumented
- .disable_at_exit_handlers! ⇒ undocumented

  Disables AtExit handlers including pool auto-termination handlers.

- .executor(executor_identifier) ⇒ Executor

  General access point to global executors.

- .global_fast_executor ⇒ ThreadPoolExecutor

  Global thread pool optimized for short, fast operations.

- .global_immediate_executor ⇒ undocumented
- .global_io_executor ⇒ ThreadPoolExecutor

  Global thread pool optimized for long, blocking (IO) tasks.

- .global_logger ⇒ undocumented
- .global_logger=(value) ⇒ undocumented
- .global_timer_set ⇒ Concurrent::TimerSet

  Global thread pool user for global timers.

- .leave_transaction ⇒ undocumented

  Leave a transaction without committing or aborting - see `Concurrent::atomically`.

- .monotonic_time ⇒ Float

  Returns the current time a tracked by the application monotonic clock.

- .new_fast_executor(opts = {}) ⇒ undocumented
- .new_io_executor(opts = {}) ⇒ undocumented
- .physical_processor_count ⇒ undocumented
- .processor_count ⇒ undocumented
- .use_simple_logger(level = Logger::FATAL, output = $stderr) ⇒ undocumented

  Use logger created by #create_simple_logger to log concurrent-ruby messages.

- .use_stdlib_logger(level = Logger::FATAL, output = $stderr) ⇒ undocumented deprecated Deprecated.

## Class Method Details

### .abort_transaction ⇒ `undocumented`

Abort a currently running transaction - see `Concurrent::atomically`.

Raises:

- (`Transaction::AbortError`)

    150
    151
    152

    # File 'lib/concurrent/tvar.rb', line 150

    def abort_transaction
      raise Transaction::AbortError.new
    end

### .atomically ⇒ `undocumented`

Run a block that reads and writes `TVar`s as a single atomic transaction. With respect to the value of `TVar` objects, the transaction is atomic, in that it either happens or it does not, consistent, in that the `TVar` objects involved will never enter an illegal state, and isolated, in that transactions never interfere with each other. You may recognise these properties from database transactions.

There are some very important and unusual semantics that you must be aware of:

- Most importantly, the block that you pass to atomically may be executed more than once. In most cases your code should be free of side-effects, except for via TVar.

- If an exception escapes an atomically block it will abort the transaction.

- It is undefined behaviour to use callcc or Fiber with atomically.

- If you create a new thread within an atomically, it will not be part of the transaction. Creating a thread counts as a side-effect.

Transactions within transactions are flattened to a single transaction.

Examples:

    a = new TVar(100_000)
    b = new TVar(100)

    Concurrent::atomically do
      a.value -= 10
      b.value += 10
    end

Raises:

- (`ArgumentError`)

    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147

    # File 'lib/concurrent/tvar.rb', line 93

    def atomically
      raise ArgumentError.new('no block given') unless block_given?

      # Get the current transaction

      transaction = Transaction::current

      # Are we not already in a transaction (not nested)?

      if transaction.nil?
        # New transaction

        begin
          # Retry loop

          loop do

            # Create a new transaction

            transaction = Transaction.new
            Transaction::current = transaction

            # Run the block, aborting on exceptions

            begin
              result = yield
            rescue Transaction::AbortError => e
              transaction.abort
              result = Transaction::ABORTED
            rescue Transaction::LeaveError => e
              transaction.abort
              break result
            rescue => e
              transaction.abort
              raise e
            end
            # If we can commit, break out of the loop

            if result != Transaction::ABORTED
              if transaction.commit
                break result
              end
            end
          end
        ensure
          # Clear the current transaction

          Transaction::current = nil
        end
      else
        # Nested transaction - flatten it and just run the block

        yield
      end
    end

### .call_dataflow(method, executor, *inputs, &block) ⇒ `undocumented`

Raises:

- (`ArgumentError`)

    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79

    # File 'lib/concurrent/dataflow.rb', line 56

    def call_dataflow(method, executor, *inputs, &block)
      raise ArgumentError.new('an executor must be provided') if executor.nil?
      raise ArgumentError.new('no block given') unless block_given?
      unless inputs.all? { |input| input.is_a? IVar }
        raise ArgumentError.new("Not all dependencies are IVars.\nDependencies: #{ inputs.inspect }")
      end

      result = Future.new(executor: executor) do
        values = inputs.map { |input| input.send(method) }
        block.call(*values)
      end

      if inputs.empty?
        result.execute
      else
        counter = DependencyCounter.new(inputs.size) { result.execute }

        inputs.each do |input|
          input.add_observer counter
        end
      end

      result
    end

### .create_simple_logger(level = Logger::FATAL, output = $stderr) ⇒ `Logger`

Returns Logger with provided level and output.

Returns:

- (`Logger`) —

  Logger with provided level and output.

    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42

    # File 'lib/concurrent/configuration.rb', line 19

    def self.create_simple_logger(level = Logger::FATAL, output = $stderr)
      # TODO (pitr-ch 24-Dec-2016): figure out why it had to be replaced, stdlogger was deadlocking
      lambda do |severity, progname, message = nil, &block|
        return false if severity < level

        message           = block ? block.call : message
        formatted_message = case message
                            when String
                              message
                            when Exception
                              format "%s (%s)\n%s",
                                     message.message, message.class, (message.backtrace || []).join("\n")
                            else
                              message.inspect
                            end

        output.print format "[%s] %5s -- %s: %s\n",
                            Time.now.strftime('%Y-%m-%d %H:%M:%S.%L'),
                            Logger::SEV_LABEL[severity],
                            progname,
                            formatted_message
        true
      end
    end

### .create_stdlib_logger(level = Logger::FATAL, output = $stderr) ⇒ `Logger`

Deprecated.

Returns Logger with provided level and output.

Returns:

- (`Logger`) —

  Logger with provided level and output.

    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74

    # File 'lib/concurrent/configuration.rb', line 51

    def self.create_stdlib_logger(level = Logger::FATAL, output = $stderr)
      logger           = Logger.new(output)
      logger.level     = level
      logger.formatter = lambda do |severity, datetime, progname, msg|
        formatted_message = case msg
                            when String
                              msg
                            when Exception
                              format "%s (%s)\n%s",
                                     msg.message, msg.class, (msg.backtrace || []).join("\n")
                            else
                              msg.inspect
                            end
        format "[%s] %5s -- %s: %s\n",
               datetime.strftime('%Y-%m-%d %H:%M:%S.%L'),
               severity,
               progname,
               formatted_message
      end

      lambda do |loglevel, progname, message = nil, &block|
        logger.add loglevel, message, progname, &block
      end
    end

### .dataflow(*inputs) {|inputs| ... } ⇒ `Object`

Dataflow allows you to create a task that will be scheduled when all of its data dependencies are available. Data dependencies are `Future` values. The dataflow task itself is also a `Future` value, so you can build up a graph of these tasks, each of which is run when all the data and other tasks it depends on are available or completed.

Our syntax is somewhat related to that of Akka's `flow` and Habanero Java's `DataDrivenFuture`. However unlike Akka we don't schedule a task at all until it is ready to run, and unlike Habanero Java we pass the data values into the task instead of dereferencing them again in the task.

The theory of dataflow goes back to the 70s. In the terminology of the literature, our implementation is coarse-grained, in that each task can be many instructions, and dynamic in that you can create more tasks within other tasks.

### Example

A dataflow task is created with the `dataflow` method, passing in a block.

    task = Concurrent::dataflow { 14 }

This produces a simple `Future` value. The task will run immediately, as it has no dependencies. We can also specify `Future` values that must be available before a task will run. When we do this we get the value of those futures passed to our block.

    a = Concurrent::dataflow { 1 }
    b = Concurrent::dataflow { 2 }
    c = Concurrent::dataflow(a, b) { |av, bv| av + bv }

Using the `dataflow` method you can build up a directed acyclic graph (DAG) of tasks that depend on each other, and have the tasks run as soon as their dependencies are ready and there is CPU capacity to schedule them. This can help you create a program that uses more of the CPU resources available to you.

### Derivation

This section describes how we could derive dataflow from other primitives in this library.

Consider a naive fibonacci calculator.

    def fib(n)
      if n < 2
        n
      else
        fib(n - 1) + fib(n - 2)
      end
    end

    puts fib(14) #=> 377

We could modify this to use futures.

    def fib(n)
      if n < 2
        Concurrent::Future.new { n }
      else
        n1 = fib(n - 1).execute
        n2 = fib(n - 2).execute
        Concurrent::Future.new { n1.value + n2.value }
      end
    end

    f = fib(14) #=> #<Concurrent::Future:0x000001019ef5a0 ...
    f.execute   #=> #<Concurrent::Future:0x000001019ef5a0 ...

    sleep(0.5)

    puts f.value #=> 377

One of the drawbacks of this approach is that all the futures start, and then most of them immediately block on their dependencies. We know that there's no point executing those futures until their dependencies are ready, so let's not execute each future until all their dependencies are ready.

To do this we'll create an object that counts the number of times it observes a future finishing before it does something - and for us that something will be to execute the next future.

    class CountingObserver

      def initialize(count, &block)
        @count = count
        @block = block
      end

      def update(time, value, reason)
        @count -= 1

        if @count <= 0
          @block.call()
        end
      end

    end

    def fib(n)
      if n < 2
        Concurrent::Future.new { n }.execute
      else
        n1 = fib(n - 1)
        n2 = fib(n - 2)

        result = Concurrent::Future.new { n1.value + n2.value }

        barrier = CountingObserver.new(2) { result.execute }
        n1.add_observer barrier
        n2.add_observer barrier

        n1.execute
        n2.execute

        result
      end
    end

We can wrap this up in a dataflow utility.

    f = fib(14) #=> #<Concurrent::Future:0x00000101fca308 ...
    sleep(0.5)

    puts f.value #=> 377

    def dataflow(*inputs, &block)
      result = Concurrent::Future.new(&block)

      if inputs.empty?
        result.execute
      else
        barrier = CountingObserver.new(inputs.size) { result.execute }

        inputs.each do |input|
          input.add_observer barrier
        end
      end

      result
    end

    def fib(n)
      if n < 2
        dataflow { n }
      else
        n1 = fib(n - 1)
        n2 = fib(n - 2)
        dataflow(n1, n2) { n1.value + n2.value }
      end
    end

    f = fib(14) #=> #<Concurrent::Future:0x00000101fca308 ...
    sleep(0.5)

    puts f.value #=> 377

Since we know that the futures the dataflow computation depends on are already going to be available when the future is executed, we might as well pass the values into the block so we don't have to reference the futures inside the block. This allows us to write the dataflow block as straight non-concurrent code without reference to futures.

    def dataflow(*inputs, &block)
      result = Concurrent::Future.new do
        values = inputs.map { |input| input.value }
        block.call(*values)
      end

      if inputs.empty?
        result.execute
      else
        barrier = CountingObserver.new(inputs.size) { result.execute }

        inputs.each do |input|
          input.add_observer barrier
        end
      end

      result
    end

    def fib(n)
      if n < 2
        Concurrent::dataflow { n }
      else
        n1 = fib(n - 1)
        n2 = fib(n - 2)
        Concurrent::dataflow(n1, n2) { |v1, v2| v1 + v2 }
      end
    end

    f = fib(14) #=> #<Concurrent::Future:0x000001019a26d8 ...
    sleep(0.5)

    puts f.value #=> 377

Parameters:

- inputs (`Future`) —

  zero or more `Future` operations that this dataflow depends upon

Yields:

- The operation to perform once all the dependencies are met

Yield Parameters:

- inputs (`Future`) —

  each of the `Future` inputs to the dataflow

Yield Returns:

- (`Object`) —

  the result of the block operation

Returns:

- (`Object`) —

  the result of all the operations

Raises:

- (`ArgumentError`) —

  if any of the inputs are not `IVar`s

- (`ArgumentError`) —

  if no block is given

    34
    35
    36

    # File 'lib/concurrent/dataflow.rb', line 34

    def dataflow(*inputs, &block)
      dataflow_with(Concurrent.global_io_executor, *inputs, &block)
    end

### .dataflow!(*inputs, &block) ⇒ `undocumented`

    44
    45
    46

    # File 'lib/concurrent/dataflow.rb', line 44

    def dataflow!(*inputs, &block)
      dataflow_with!(Concurrent.global_io_executor, *inputs, &block)
    end

### .dataflow_with(executor, *inputs, &block) ⇒ `undocumented`

    39
    40
    41

    # File 'lib/concurrent/dataflow.rb', line 39

    def dataflow_with(executor, *inputs, &block)
      call_dataflow(:value, executor, *inputs, &block)
    end

### .dataflow_with!(executor, *inputs, &block) ⇒ `undocumented`

    49
    50
    51

    # File 'lib/concurrent/dataflow.rb', line 49

    def dataflow_with!(executor, *inputs, &block)
      call_dataflow(:value!, executor, *inputs, &block)
    end

### .disable_at_exit_handlers! ⇒ `undocumented`

Note:

this option should be needed only because of `at_exit` ordering issues which may arise when running some of the testing frameworks. E.g. Minitest's test-suite runs itself in `at_exit` callback which executes after the pools are already terminated. Then auto termination needs to be disabled and called manually after test-suite ends.

Note:

This method should never be called from within a gem. It should only be used from within the main application and even then it should be used only when necessary.

Disables AtExit handlers including pool auto-termination handlers. When disabled it will be the application programmer's responsibility to ensure that the handlers are shutdown properly prior to application exit by calling AtExitImplementation.new.install.run method.

See Also:

- AtExit

    129
    130
    131

    # File 'lib/concurrent/configuration.rb', line 129

    def self.disable_at_exit_handlers!
      AtExit.enabled = false
    end

### .executor(executor_identifier) ⇒ `Executor`

General access point to global executors.

Parameters:

- executor_identifier (`Symbol`, `Executor`) —

  symbols:

  - :fast - global_fast_executor
  - :io - global_io_executor
  - :immediate - global_immediate_executor

Returns:

- (`Executor`)

    164
    165
    166

    # File 'lib/concurrent/configuration.rb', line 164

    def self.executor(executor_identifier)
      Options.executor(executor_identifier)
    end

### .global_fast_executor ⇒ `ThreadPoolExecutor`

Global thread pool optimized for short, fast operations.

Returns:

- (`ThreadPoolExecutor`) —

  the thread pool

    136
    137
    138

    # File 'lib/concurrent/configuration.rb', line 136

    def self.global_fast_executor
      GLOBAL_FAST_EXECUTOR.value
    end

### .global_immediate_executor ⇒ `undocumented`

    147
    148
    149

    # File 'lib/concurrent/configuration.rb', line 147

    def self.global_immediate_executor
      GLOBAL_IMMEDIATE_EXECUTOR
    end

### .global_io_executor ⇒ `ThreadPoolExecutor`

Global thread pool optimized for long, blocking (IO) tasks.

Returns:

- (`ThreadPoolExecutor`) —

  the thread pool

    143
    144
    145

    # File 'lib/concurrent/configuration.rb', line 143

    def self.global_io_executor
      GLOBAL_IO_EXECUTOR.value
    end

### .global_logger ⇒ `undocumented`

    91
    92
    93

    # File 'lib/concurrent/configuration.rb', line 91

    def self.global_logger
      GLOBAL_LOGGER.value
    end

### .global_logger=(value) ⇒ `undocumented`

    95
    96
    97

    # File 'lib/concurrent/configuration.rb', line 95

    def self.global_logger=(value)
      GLOBAL_LOGGER.value = value
    end

### .global_timer_set ⇒ `Concurrent::TimerSet`

Global thread pool user for global timers.

Returns:

- (`Concurrent::TimerSet`) —

  the thread pool

    154
    155
    156

    # File 'lib/concurrent/configuration.rb', line 154

    def self.global_timer_set
      GLOBAL_TIMER_SET.value
    end

### .leave_transaction ⇒ `undocumented`

Leave a transaction without committing or aborting - see `Concurrent::atomically`.

Raises:

- (`Transaction::LeaveError`)

    155
    156
    157

    # File 'lib/concurrent/tvar.rb', line 155

    def leave_transaction
      raise Transaction::LeaveError.new
    end

### .monotonic_time ⇒ `Float`

Note:

Time calculations on all platforms and languages are sensitive to changes to the system clock. To alleviate the potential problems associated with changing the system clock while an application is running, most modern operating systems provide a monotonic clock that operates independently of the system clock. A monotonic clock cannot be used to determine human-friendly clock times. A monotonic clock is used exclusively for calculating time intervals. Not all Ruby platforms provide access to an operating system monotonic clock. On these platforms a pure-Ruby monotonic clock will be used as a fallback. An operating system monotonic clock is both faster and more reliable than the pure-Ruby implementation. The pure-Ruby implementation should be fast and reliable enough for most non-realtime operations. At this time the common Ruby platforms that provide access to an operating system monotonic clock are MRI 2.1 and above and JRuby (all versions).

Returns the current time a tracked by the application monotonic clock.

Returns:

- (`Float`) —

  The current monotonic time since some unspecified starting point

See Also:

- Linux clock_gettime(3)

    53
    54
    55

    # File 'lib/concurrent/utility/monotonic_time.rb', line 53

    def monotonic_time
      GLOBAL_MONOTONIC_CLOCK.get_time
    end

### .new_fast_executor(opts = {}) ⇒ `undocumented`

    168
    169
    170
    171
    172
    173
    174
    175
    176

    # File 'lib/concurrent/configuration.rb', line 168

    def self.new_fast_executor(opts = {})
      FixedThreadPool.new(
          [2, Concurrent.processor_count].max,
          auto_terminate:  opts.fetch(:auto_terminate, true),
          idletime:        60, # 1 minute
          max_queue:       0, # unlimited
          fallback_policy: :abort # shouldn't matter -- 0 max queue
      )
    end

### .new_io_executor(opts = {}) ⇒ `undocumented`

    178
    179
    180
    181
    182
    183

    # File 'lib/concurrent/configuration.rb', line 178

    def self.new_io_executor(opts = {})
      CachedThreadPool.new(
          auto_terminate:  opts.fetch(:auto_terminate, true),
          fallback_policy: :abort # shouldn't matter -- 0 max queue
      )
    end

### .physical_processor_count ⇒ `undocumented`

    155
    156
    157

    # File 'lib/concurrent/utility/processor_counter.rb', line 155

    def self.physical_processor_count
      processor_counter.physical_processor_count
    end

### .processor_count ⇒ `undocumented`

    151
    152
    153

    # File 'lib/concurrent/utility/processor_counter.rb', line 151

    def self.processor_count
      processor_counter.processor_count
    end

### .use_simple_logger(level = Logger::FATAL, output = $stderr) ⇒ `undocumented`

Use logger created by #create_simple_logger to log concurrent-ruby messages.

    45
    46
    47

    # File 'lib/concurrent/configuration.rb', line 45

    def self.use_simple_logger(level = Logger::FATAL, output = $stderr)
      Concurrent.global_logger = create_simple_logger level, output
    end

### .use_stdlib_logger(level = Logger::FATAL, output = $stderr) ⇒ `undocumented`

Deprecated.

Use logger created by #create_stdlib_logger to log concurrent-ruby messages.

    78
    79
    80

    # File 'lib/concurrent/configuration.rb', line 78

    def self.use_stdlib_logger(level = Logger::FATAL, output = $stderr)
      Concurrent.global_logger = create_stdlib_logger level, output
    end