Java and Contract summary

Source: Internet
Author: User

Java and contract

In addition to providing high-performance thread-Safe collection objects, the package also provides a number of atomic operations classes required for concurrent scenarios, such as Atomicinteger, and also provides some lock and condition classes to avoid concurrency-time resource conflicts.

Concurrenthashmap

Implementation of thread-safe hashmap.
Maintains an array of segment objects, segment inherits Reentrantlock

Method meaning
Concurrenthashmap ()
Put (Object key,object value) Concurrenthashmap divides multiple segment based on Concurrencylevel to store key-velue, thus avoiding locking the entire array for each put operation. By default, the best case scenario allows 16 threads to be able to concurrently block an action collection object without blocking
Remove (Object key)
Get (Object)
ContainsKey (Object key)
KeySet (). Iterator ()
Copyonwritearraylist

Copyonwritearraylist is a thread-safe, and ArrayList without locks during read operations
It is more appropriate to read and write less and have a large number of threads.

    • Copyonwritearraylist ()
      Unlike ArrayList, create an array of size 0

    • Add ()
      Use Reentrantlock to ensure thread safety, and each time a new object array is created, the size of the array is the current array size plus 1, the contents of the previous array are copied to the new array, and the newly added objects are placed at the end of the array. The last reference switch assigns the newly created array object to the global array object

    • Remove (E)
      The first is to ensure thread safety through reentrantlock, then delete, and delete is different from ArrayList.
    • Get (int)
      It's possible to read dirty data
    • Iterator
Copyonwritearrayset

Based on the Copyonwritearraylist implementation, the only difference is that the Copyonwritearraylist Addifabsent method is called at add
Copyonwritearrayset performs an array traversal every time at add, so performance is slightly lower than copyonwritearraylist.

Arrayblockingqueue

A bounded blocking queue supported by the array. This queue sorts elements by FIFO (first-in, in-out) principle. The head of the queue is the element that has the longest time in the queue. The tail of the queue is the element that has the shortest time in the queue. The new element is inserted at the end of the queue, and the queue fetch operation starts from the head of the queue to get the element.

This is a typical "bounded buffer", in which the fixed-size array keeps the elements inserted by the producer and the user extracts the elements. Once such a buffer is created, it is no longer possible to increase its capacity. Attempting to put an element into the full queue causes the operation to be blocked, and attempting to extract elements from the empty queue will cause similar blocking.

    • Arrayblockingqueue (int)
    • Offer (E,long,timeunit)
      Inserts the specified element into the tail of this queue and, if the queue is full, waits for the available space before reaching the specified wait time.
    • Poll (Long,timeunit)
      Gets and removes the header of this queue, waiting for the available elements (if necessary) before the specified wait time.
    • Put (E)
      Inserts the specified element at the end of this queue and waits for available space if the queue is full.
    • Take ()
      Gets and removes the head of this queue, waiting until the element becomes available (if necessary).
Atomicinteger

An integer class that supports atomic operations,

    • Atomicinteger ()
      Creates a new Atomicinteger with an initial value of 0.
    • Atomicinteger (int initialvalue)
      Creates a new Atomicinteger with the given initial value.
    • int addandget (int delta)
      Adds the given value in atomic form to the current value.
    • int Decrementandget ()
      atomically subtract the current value by 1.
    • int Incrementandget ()
      Atomically adds 1 to the current value.
    • Get ()
      Gets the current value.
    • Set (int newvalue)
      Set to the given value.
Executors

Create a thread pool

    • Newfixedthreadpool (int)
    • Newcachedthreadpool ()
    • Newsinglethreadpool ()
Futuretask

Can be used to asynchronously get the execution result or cancel the execution of the task of the scene, by passing in runnable or callable task to Futuretask, directly call its run method or put into the thread pool execution, after the external through the Futuretask get asynchronous get execution results. Futuretask ensures that even if multiple run methods are called, it performs a runnable or callable task, or cancels futuretask execution by cancle.

Method meaning
Futuretask (callable callable) Creates a futuretask that executes the given callable once it is run.
Futuretask (Runnable Runnable, V result) Creates a futuretask that, once run, executes the given Runnable and schedules a successful completion when get returns the given result.
Boolean Cancel (Boolean mayinterruptifrunning) An attempt was made to cancel execution of this task.
protected void Done () The protected method is called when this task transitions to the state isDone (whether normal or canceled).
V get () If necessary, wait for the calculation to complete and then get its results.
V get (long timeout, timeunit unit) If necessary, wait for the result to be obtained (if the result is available) after the time given for the calculation to complete.
Boolean iscancelled () Returns true if the task is canceled before it is completed properly.
Boolean IsDone () Returns true if the task is completed.
void Run () Unless you have canceled this future, set it as the result of its calculation.
Protected Boolean Runandreset () Performs a calculation without setting its results, resets the future to its original state, and fails if the calculation encounters an exception or is canceled.
protected void Set (V V) The result is set to the given value unless the future has been set or canceled.
Semaphore

A count semaphore. Conceptually, semaphores maintain a set of licenses. If necessary, block each acquire () before the license is available, and then obtain the license. Each release () adds a license that may release a blocked fetch.

Method meaning
Semaphore (int permits) Creates a Semaphore with the given number of licenses and unfair fairness settings.
Semaphore (int permits, Boolean fair) Creates a Semaphore with the given number of licenses and a given fairness setting.
void Acquire () Obtain a license from this semaphore to block the thread until a license is provided, or the thread is interrupted.
void Release () Release a license to return it to the semaphore.
public boolean Tryacquire () A license is obtained from the semaphore only if there is one available license for this semaphore at the time of invocation. (Get permission Now)
Countdownlatch

Initializes the countdownlatch with the given count. Because the countdown () method is called, the await method is blocked until the current count reaches 0. After that, all the waiting threads are freed, and all subsequent calls to await are returned immediately. This behavior occurs only once-the count cannot be reset.

Method meaning
void await () Causes the current thread to wait until the latch is counted down to 0, unless the thread is interrupted.
Boolean await (long timeout, timeunit unit) Causes the current thread to wait until the latch is counted down to 0, unless the thread is interrupted or the specified wait time is exceeded.
void Countdown () Decrements the latch count and, if the count reaches 0, releases all waiting threads.
Long GetCount () Returns the current count.
String toString () Returns a string that identifies this latch and its status.
Cyclicbarrier

Unlike the Cyclicbarrier and Countdownlatch, Cyclicbarrier is the number of await that has reached the set number before it continues to execute.
The barrier can be reused after releasing the waiting thread, so it is called a cyclic barrier.

Method meaning
Cyclicbarrier (int parties) Creates a new cyclicbarrier that starts when a given number of participants (threads) are waiting, but does not perform a predefined operation when the barrier is started.
int await () Wait until all participants have already raised the await method in this barrier.
Reentrantlock

A reentrant mutex lock, which has the same basic behavior and semantics as the implicit monitor lock accessed using the Synchronized method and the statement, but is more powerful.

Method meaning
Reentrantlock () Creates an instance of a reentrantlock.
void Lock () Gets the lock.
void Unlock () An attempt was made to release this lock.
Condition newcondition () Returns the Condition instance used with this Lock instance.
Condition

A condition (also known as a conditional queue or condition variable) provides a means for a thread to suspend the thread (that is, let it "wait") until another thread that a state condition might now be true notifies it.
The Condition instance is essentially bound to a lock. To obtain an Condition instance for a particular Lock instance, use its newcondition () method.

    • void await ()
      The current thread waits until the signal is received or interrupted.
    • void Signal ()
      Wakes up a waiting thread.
    • void Signalall ()
      Wakes all waiting threads.
Reentrantreadwritelock

A read-write lock that supports up to 65,535 recursive write locks and 65,535 read locks. Attempting to exceed these limits will cause the lock method to throw an Error.
Easy to implement reader-writer questions

Method meaning
Reentrantreadwritelock.readlock Readlock () Returns the lock used for the read operation.
Reentrantreadwritelock.writelock Writelock () Returns the lock used for the write operation.
Reentrantreadwritelock.readlock
    • Lock ()
    • Unlock ()
Reentrantreadwritelock.writelock
    • Lock ()
    • Unlock ()
Exchager

The synchronization point of the thread that can pair and swap elements in pairs. Each thread renders a method on the entry to the Exchange method, matches the partner thread, and receives the object of its partner when it returns. Exchanger may be considered a bidirectional form of synchronousqueue. Exchanger may be useful in applications such as genetic algorithms and pipeline design.

Exchanger<v>
V-Types of objects that can be exchanged

Method meaning
Exchanger () Create a new Exchanger.
V Exchange (v x) Waits for another thread to reach this interchange point (unless the current thread is interrupted), then routes the given object to that thread and receives the object for that thread.
V Exchange (v X, long timeout, timeunit unit) Waits for another thread to reach this interchange point (unless the current thread is interrupted, or the specified wait time is exceeded), and then the given object is passed to the thread, and the object of the thread is received.
Summarize
  1. collection classes under the Concurrency framework:

    • Arrayblockingqueue: A bounded blocking queue that can implement producer-consumer issues
    • A thread-safe variant of copyonwritearraylist:arraylist, where all mutable operations (add, set, and so on) are implemented by a new copy of the underlying array.
    • Copyonwritearrayset: most suitable for applications with the following characteristics: The set size is usually kept small, read-only operations are much larger than mutable operations, and there is a need to prevent conflicts between threads during traversal.
    • Linkedblockingqueue: The throughput of a linked queue is typically higher than an array-based queue, but in most concurrent applications, its predictable performance is low.
    • Concurrentlinkedqueue: Non-boundary thread secure queue based on link node
    • Concurrenthashmap: Thread-safe HASHMAP implementation
  2. Tool class

    • Countdownlatch
    • Cyclicbarrier
      Cyclic: cyclic, Periodic

    Both of these tool classes can be used to implement a thread that waits for multiple threads to end, ensuring that almost all threads execute concurrently

  3. Atomic operation

    • Atomicinteger
    • Atomicboolean
    • ...
  4. Get the return value of another thread

    • Callable
    • Futuretask
  5. Resource competition

    • Semphore
  6. Mutually exclusive

    • Reentrantlock
    • Condition
    • Reentrantreadwritelock
    • Reentrantreadwritelock.writelock
    • Reentrantreadwritelock.readlock

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java and Contract summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.