Java Multi-threaded---synchronization and lock

Source: Internet
Author: User
Tags throw exception throwable

One, thread synchronization is the damage to the data that prevents multiple threads from accessing a data object.

Second, sync and lock

1, the principle of the lock

Each object in Java has a built-in lock.

When the program runs to a non-static synchronized synchronization method, the lock associated with the current instance (this instance) of the executing code class is automatically obtained. Acquiring a lock on an object is also known as acquiring a lock, locking an object, locking on an object, or synchronizing on an object.

The object lock does not work when the program runs to the synchronized synchronization method or code block.

An object has only one lock. Therefore, if a thread obtains the lock, no other thread can get the lock until the first thread releases (or returns) the lock. This also means that no other thread can enter the synchronized method or block of code on the object until the lock is freed.

A release lock is a lock thread that exits the synchronized synchronization method or code block.

About locks and synchronizations, there are a few key points:
1), can only synchronize methods, and cannot synchronize variables and classes,
2), each object has only one lock; when it comes to synchronization, what should be clearly synchronized? In other words, on which object is it synchronized?
3), you do not have to synchronize all the methods in the class, and the class can have both synchronous and non-synchronous methods.
4), if two threads are to execute the synchronized method in a class, and two threads use the same instance to invoke the method, only one thread can execute the method at a time, and the other waits until the lock is freed. That is, if a thread obtains a lock on the object, no other thread can enter any one of the synchronization methods in the class (the object).
5), if the thread has synchronous and non-synchronous methods, the non-synchronous method can be freely accessed by multiple threads without being restricted by the lock.
6), when the thread sleeps, any locks it holds are not freed.
7), the thread can obtain multiple locks. For example, a synchronous method that invokes another object in a synchronous method of an object acquires a synchronization lock for two objects.
8), synchronization damage concurrency, should be as narrow as possible synchronization range. Synchronization can not only synchronize the entire method, but also synchronize some of the code blocks in the method.
9), when using a synchronous block of code, you should specify which object to synchronize on, that is, which object to get the lock. Example:
public int, fix (int y) {
      synchronized (this) {
            x = XY;
     }
      return x;
}

Of course, synchronous methods can also be rewritten as non-synchronous methods, but functionally identical, for example:
public synchronized int GetX () {
return x + +;
}
And
public int GetX () {
Synchronized (this) {
return x + +;
}
}
The effect is exactly the same.

Third, static method synchronization

To synchronize a static method, you need a lock for the entire class object, which is the Class (Xxx.class).
For example:
public static synchronized int setName (String name) {
Xxx.name = name;
}
Equivalent to
public static int SetName (String name) {
Synchronized (Xxx.class) {
Xxx.name = name;
}
}

Iv. What happens if a thread can't get a lock

If a thread attempts to enter the synchronization method and its lock is already occupied, the thread is blocked on the object. Essentially, a thread enters a pool of that object, where it must wait until its lock is freed and the thread becomes operational or running again.

When considering blocking, be sure to note which object is being used for locking:
1. Threads that call non-static synchronization methods on the same object will block each other. If it is a different object, each thread has its own lock on the object, and the threads do not interfere with each other.
2. Threads that call static synchronization methods in the same class will block each other, and they are all locked on identical class objects.
3. Static synchronization methods and non-static synchronization methods will never block each other, because static methods are locked on the class object, and non-static methods are locked on the object of the class.
4, for the synchronization of the code block, to see what the object has been used to lock (synchronized the contents of the parentheses behind). Threads that synchronize on the same object block each other, and threads that are locked on different objects will never block each other.

Five. When to synchronize

When multiple threads access mutually exclusive (exchangeable) data, they should be synchronized to protect the data, ensuring that two threads do not modify it at the same time.

For data that can be changed in non-static fields, it is usually accessed using a non-static method.
For data that can be changed in a static field, it is usually accessed using static methods.

If you need to use a static field in a non-static method, or if you call a non-static method in a static field, the problem becomes very complex. Has gone beyond the scope of the SJCP exam.

Vi. Thread Safety Classes

When a class is already well synchronized to protect its data, this class is called "Thread-safe."

Even thread-safe classes should be particularly cautious, because the threads of the operation are still not necessarily secure.

Vii. Thread Synchronization Summary

1, the purpose of thread synchronization is to protect multiple threads to access a resource when the resource is destroyed.
2, thread synchronization method is implemented by the lock, each object has a cut only a lock, the lock with a specific object, the thread once the object lock, the other access to the object's thread can no longer access the object's other synchronization methods.
3, for the static synchronization method, the lock is for this class, the lock object is the class object. Static and non-static methods of locking do not interfere. A thread acquires the lock, which is obtained when a synchronization method on another object is accessed in a synchronous method.
4, for synchronization, to be awake at all times on which object synchronization, this is the key.
5, write thread-safe classes, you need to pay attention to multiple threads competing access to the logic and security of the resources to make the right judgment, the "atomic" operation to make an analysis, and ensure that other threads during atomic operation can not access the competing resources.
6. When multiple threads wait for an object lock, the thread that does not acquire the lock will block.
7, deadlock is between the threads waiting for lock-lock caused by, in practice, the probability of occurring is very small.

Synchronizing code blocks:
    Synchronized (object) {
        Synchronizing code
    }
    Java multithreading Support method synchronization, method synchronization only use synchronized to modify the method, then this method is the synchronization method.
    For synchronous methods, you do not need to display the specified synchronization monitor, the synchronous method monitor is itself this
    Synchronization method:
    Public synchronized void Editbythread () {
        DoSomething
    }
    Classes that require synchronization methods have the following characteristics:
    A, objects of this class can be accessed by multiple threads
    B, each thread call object can end normally, return to normal result
    C. After each thread invokes any method of the object, the state of the object remains in a reasonable state
    Immutable classes are always thread-safe because their object state is immutable, but mutable class objects require additional methods to ensure thread safety.
    For example, the account is a mutable class, and its money is mutable, and when 2 threads modify money at the same time, the program will have an exception or an error.
    So to set the account to thread-safe, you need to use the sync synchronized keyword.
    
    
    The following method uses synchronized to synchronize the keyword modifiers, so this method is a synchronous method. So that only one thread can access this method,
    When this method is called by the current thread, this method is locked and the synchronization monitor is this. This method can only be called by other threads when this method has been modified.
    In this way, the security of threads can be ensured, and the security of multi-thread and money-fetching is handled.
    Public synchronized void Drawmoney (double money) {
        Withdraw Money operation
    }
    Note: Synchronized can modify methods, blocks of code, but cannot modify properties, construct methods
    
    In order to reduce the negative impact of thread safety, the thread safety of a mutable class is to reduce the operational efficiency of the program, and the following strategies can be used:
    A, do not use synchronous mode for all methods of the thread-safe class, and only synchronize the methods that will change the competing resources (shared resources).
    B, if the variable class has 2 in the running environment: single-threaded environment and multi-threaded environment, you should provide 2 versions of the variable, thread-safe and non-thread-safe version.
    It adopts non-thread-safe to improve the performance of running efficiency under single thread, and adopts thread-safe control security problem in multi-threaded environment.
    
    Release the lock on the sync monitor
    When any thread enters a synchronous code block or synchronization method, it must first obtain a lock on the synchronization monitor, and when will it release the Sync Monitor lock?
    The program cannot display the release lock on the synchronization monitor, and the thread can release the lock in the following ways:
    A, when the synchronization method of the thread, the synchronization code base execution ends, you can release the synchronization monitor
    B, when the thread in the synchronization code base, the method encountered a break, return termination code run, can also release
    C, when the thread in the synchronization code base, the synchronization method encountered an unhandled error, Exception, resulting in the end of the code can also release the synchronization monitor
    D. When the thread is synchronizing the code base, the synchronization method, the program executes the wait method of the synchronization monitor object, causes the method to pause, releases the synchronization monitor
    The synchronization monitor is not released under the following conditions:
    A, when the thread executes the synchronization code base, the synchronization method, the program calls the Thread.Sleep ()/thread.yield () method to pause the current program, the current program does not release the synchronization monitor
    B, when a thread executes a synchronous code base, a synchronization method, another thread calls the thread's suspend method to suspend the thread, and the thread does not release the synchronization monitor. Be careful to avoid using suspend, resume
    
    Sync Lock (Lock)
    It is generally thought that lock provides a wider range of locking operations than the Synchronized method and synchronized code block, a more flexible structure for lock, a great difference, and can support multiple condition objects
    Lock is a tool that controls the access of multiple threads to shared resources. Typically, a lock provides exclusive access to a shared resource, and only one thread can lock the lock object at a time.
    The lock object should be obtained before the thread starts accessing the shared resource. However, some locks support concurrent access to shared resources, such as: Readwritelock (read-write lock), thread security control,
    Typically, Reentrantlock (reentrant locks) are used. Use this lock object to display locking, release locks.
     
    Class C {
        Lock Object
        Private final Reentrantlock lock = new Reentrantlock ();
        ......
        Securing a thread-safe approach
        public void Method () {
            Locked
            Lock.lock ();
            try {
                Ensure thread-safe operation code
            } catch () {
            
            } finally {
                Lock.unlock ();//Release lock
            }
        }
    }
    When using the lock object for synchronization, the lock and release locks are placed in the finally to ensure that the release lock is performed.
    
    Using locks and using synchronization is very similar, just using the lock method that is displayed when you synchronize. When using the synchronous method synchronized, the system implicitly uses the current object as the synchronization monitor.
    It is also the "lock-on, access-and release-lock" operation mode, which guarantees that only one thread can manipulate resources.
    Synchronous methods and synchronous code blocks use a competing resource-dependent, implicit synchronization monitor, and force lock and release locks to appear in a block structure, and when multiple locks are obtained,
    They must be released in reverse order, and all resources must be released in the same scope as all locks are fetched.
    Lock provides the synchronization method and other features that the synchronization code base does not have, including the Trylock method for non-block structures, which has attempted to obtain the interruptible lock lockinterruptibly () method,
    There is also a trylock (long, timeunit) method that gets the timeout expiration lock.
    The Reentrantlock is reentrant, which means that the thread can lock the reentrantlock that it has been locked again, and the Reentrantlock object maintains a counter to track the nested calls of the lock method.
    After each call to lock (), the thread must display the call unlock () to release the lock, so a piece of protected code can invoke another method that is protected by the same lock.
    
    Dead lock
    A deadlock occurs when 2 threads wait for each other to synchronize the monitor, and the JVM does not take steps to handle deadlocks, which requires us to handle or avoid deadlocks ourselves.
    Once a deadlock occurs, the entire program will not have an exception or error and prompt, but the thread will be in a blocked state and cannot continue.
    The main thread keeps the lock on Foo, waits for the bar object to be locked, while the secondary thread remains locked on the bar object, waiting for the Foo lock 2 threads to wait for each other to release the lock before entering the deadlock state.
    Because the suspend of the thread class can also easily lead to deadlocks, Java does not recommend this method to suspend threads.
13. Thread Communication
    (1), the coordinated operation of the thread
        Scenario: With 2 threads, these 2 threads represent deposits and withdrawals, respectively. --Now the system requires depositors and withdrawals to repeat the actions of deposits and withdrawals,
        And every time a depositor deposits money into an account, the teller immediately takes out the money. 2 consecutive deposits and 2 consecutive withdrawals are not allowed.
        Implementing the above scenario requires the object class, which provides three methods of wait, notify, and Notifyall, which are not part of the thread class. However, these 3 methods must be called by the synchronization monitor and can be divided into 2 cases:
        A, for a synchronization method that uses the synchronized adornment, because the default instance of this class is the synchronization monitor, you can call these 3 methods directly in the synchronization.
        B, for synchronous code blocks modified with synchronized, the synchronization monitor is an object in parentheses after synchronized, so you must use the object in parentheses to call these 3 methods
        Method Overview:
        One, wait method: Causes the current thread to enter the wait until another thread calls the synchronization Monitor's Notify method or the Notifyall method to wake the thread.
                The Wait method has 3 forms: a parameterless wait method that waits until another thread notifies you, wait with a millisecond parameter, and waiting for a subtle parameter.
                All 2 forms are waiting to wake up after the arrival of time. The current thread that calls the wait method frees the lock on the object's synchronization monitor.
        Second, notify: wakes up a single thread waiting on this sync monitor. If all threads are waiting on this synchronization monitor, it is randomly chosen to wake up one of the threads.
            The wake-up thread can only be executed if the front-thread discards the lock on the synchronization monitor (using the Wait method).
        Notifyall: Wakes up all the threads waiting on this sync monitor. A thread that wakes up can be executed only when the front-thread discards the lock on the synchronization monitor.
    (2), conditional variable control coordination
        If the program does not use the Synchronized keyword to guarantee synchronization, but instead uses the lock object directly to ensure synchronization, there is no implicit synchronization monitor object in the system.
        You cannot use the wait, notify, Notifyall methods to reconcile the running of a process.
        When using the lock object synchronization, Java provides a condition class to maintain coordination, and using condition can make those who have already got the lock object but cannot be used together,
        Multiple wait sets (Wait-set) are provided for each object, in which case the lock replaces the synchronization method and the synchronization code block, condition the ability to override the synchronization monitor.
        The condition instance is essentially bound to a lock object, to obtain the condition instance of a particular lock instance, and to invoke the newcondition of the lock object.
        Condition class Method Description:
        One, await: similar to the wait method on the implicit synchronization monitor, causes the current program to wait until another thread calls condition's signal method and Signalall method to wake the thread.
            The await method has multiple get variants: Long Awaitnanos (long nanostimeout), void awaituninterruptibly (), Awaituntil (Date daadline)
        Second, signal: Wakes a single thread waiting on this lock object, and if all threads wait on the lock object, it chooses to wake one of the threads randomly.
            The await method can be used to wake the executing thread only when the front-thread discards the lock on the lock object.
        Signalall: Wakes all the threads waiting on this lock object. A wake-up thread can only be executed if the front thread discards the lock on the lock object.
     
    (3), using pipe flow
        Thread traffic uses a pipeline flow, and there are 3 types of pipeline flows:
        PipedInputStream, PipedOutputStream, Pipedreader and PipedWriter, and Pipe.sinkchannel and Pipe.sourcechannel,
        They are the stream's byte stream, the pipe character stream, and the pipeline channel for the new IO, respectively.
        Basic steps of pipeline circulation letter:
        A, use the new method to create A pipeline input, an output stream
        B. Connect 2 input and output streams using the Connect method of the pipeline input stream and output stream
        C. Pass the pipeline input and output stream to 2 threads respectively
        D, 2 threads can rely on their own pipeline input stream, pipeline output stream for communication
    
14. Thread groups and unhandled exceptions
    Threadgroup represents a thread group, which can represent a batch of threads for classification management, and Java allows programs to
    Java allows direct control of the thread group, which controls the batch of threads relative to the thread group. All threads created by the user belong to the specified thread group.
    If the program is not worthy of which group the thread belongs to, that thread belongs to the default thread group. By default, the child thread and the parent thread that created it belong to the same group.
    Once a thread has joined the specified thread group, the thread will belong to that thread group until the thread dies, and the thread can not change the thread group it belongs to while it is running.
    The thread class provides some construction settings for which group the thread belongs to, with the following methods:
    A, Thread (threadgroup Group, Runnable target): Target's Run method creates a new thread as the thread execution body, which belongs to group thread groups
    B, Thread (threadgroup group, Runnalbe Target, String name): The Run method of target is the new thread created by the thread execution body, which belongs to the group thread, and the thread is named name
    C, Thread (threadgroup Group, String name): Creates a new thread, the new thread is named name and belongs to the group
    Because the group that the thread belongs to cannot be changed halfway, thread provides a setter method for Threadgroup, but provides a Getthreadgroup method to return the thread group to which the thread belongs.
    The return value of the Getthreadgroup method is the representation of the Threadgroup object, which represents a thread group.
    There are 2 tectonic forms of the Threadgroup:
    A, Threadgroup (String name): Name of the thread group
    B, Threadgroup (threadgroup parent, String name): Specify a name, specify a new thread group created by the parent thread Group
    All of the above constructs specify the thread name, that is, the thread group must have its own name, which can be obtained by calling the Threadgroup GetName method.
    But it is not allowed to change names halfway. Threadgroup has the following common methods:
    A, Activecount: Returns the number of thread group active threads
    B, Interrupt: Interrupts all threads in this thread group
    C, Isdeamon: Determine if the thread is running in the background
    D, Setdeamon: Set the thread group as a background thread group, the background thread has a feature, when the last thread of the background thread executes the end or the last thread is destroyed, the background thread group is automatically destroyed.
    E, Setmaxpriority: Set the highest priority of the thread group
    Uncaughtexception (thread T, Throwable e) This method can handle unhandled exceptions thrown by threads within that thread group.
    Thread.uncaughtexceptionhandler is an internal public static interface for the thread class,
    There is only one method within the interface: void Uncaughtexception (Thread T, throwable e) The T in this method represents the thread that has the exception, and E represents the exception that the thread throws
     
    The thread class provides 2 methods to set the exception handler:
    A, Staticsetdefaultunaughtexceptionhandler (Thread.uncaughtexceptionhandler eh): Sets the default exception handler for all thread instances of the thread class
    B, Setuncaughtexceptionhandler (Thread.uncaughtexceptionhander eh): Set exception handlers for guiding thread instances
    Threadgroup implements the Thread.uncaughtexceptionhandler interface, so the thread group that each thread belongs to will be the default exception handler. When a thread throws an unhandled exception,
    The JVM first looks for the exception handler for the exception (Setuncaughtexceptionhandler sets the exception handler), and if the exception handler is found, the exception handler is called to handle the exception.
    Otherwise, the JVM will invoke the uncaughtexception of the thread group that owns the thread to handle the exception, and the thread group handles the exception flow as follows:
    A, if the line threads the parent thread group, call the parent thread group's Uncaughtexception method to handle the exception
    B, if the thread class to which the thread instance belongs has a default exception handler (the Setdefaultunaughtexceptionhandler method sets the exception handler), then the exception handler is called to handle the exception information
    C, print the information of the exception call stack to the System.err error output stream, and end the thread
15, callable and future
    The callable interface defines a call method that can act as a thread's execution, but the call method is more powerful than the Run method:
    A, the call method can have a return value
    B, call method can declare throw exception
    The callable interface is a new interface after JDK5, and is not a runnable sub-interface, so the callable object cannot be the target of thread directly. And the call method also has a return value,
    The call method cannot be called directly, it is called as the executing body of the thread. So how do I receive the return value of the call method?
    JDK1.5 provides a future interface to represent the return value of the call method in the callable interface, and provides a Futuretask implementation class for the future interface, which implements the future interface,
    and implements the Runnable interface-can be the target of thread.
    The future interface defines the following public methods to control his associated callable tasks:
    A, Boolean Cancel (Boolean mayinterruptlfrunning): Attempted to cancel the callable task associated with the future
    B, V get (): Returns the return value of the call method in the callable task, which causes the thread to block and must wait until the child thread ends to get the return value
    C, V get (long timeout, timeunit unit): Returns the return value of the call method in the callable task, which allows the program to block timeout and the time specified by the unit.
        If the callable task still has no return value after the specified time, TimeoutException will be thrown.
    D, Boolean iscancelled: Returns True if the callable task is canceled before it is properly completed.
    E, Boolean IsDone: Returns True if the callable task has completed
    The steps to create and start a thread with a return value are as follows:
    First, create an implementation class for the callable interface, and implement the Call method, the return value of the call method, and act as the thread's execution body.
    Second, create an instance of the callable implementation class, using the Futuretask class to wrap the callable object, which encapsulates the return value of the call method of the callable object
    Third, use the Futuretask object as the target of the thread object to create and start a new thread
    Iv. call the method of the Futuretask object to get the return value after the child thread execution ends

Java Multi-threaded---synchronization and lock

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.