Java Interview Reference Guide-sync

Source: Internet
Author: User
Tags modifiers volatile

Synchronous


In multithreaded programs, synchronization modifiers are used to control access to critical section code. One way is to use the Synchronized keyword to ensure thread safety for your code. In Java, synchronized-modified code blocks or methods are not accessed concurrently by multiple threads. It forces the thread to obtain a lock before entering a method, releasing the lock when it leaves the method. It guarantees that only one thread can execute the method that is modified at the same time.


If we define a method or block of code as synchronous, it means that there is only one call to the synchronous method in the same object. If a synchronous method is called inside a thread, the other threads block until the first thread finishes the method call.


Before entering the synchronization method of an object, you need to request that the object be locked, and the lock is released for other threads to request after the method call is completed. The synchronization method follows the Happens-before mechanism, which ensures that changes to the state of the object are visible in other threads.


When you mark a block of code for synchronization, you need to use an object as a parameter. When a running thread executes to the code block, wait until the other running thread exits the synchronization code area of the object. However, one thread can enter the synchronization code area of another object. However, the non-synchronous method of the same object can not request a lock.


If you define a static method for synchronization, it is synchronized on the class instead of on the object. That is, if a static synchronization method executes, the entire class is locked, and other static method calls in that class are blocked.


1) When a thread enters a synchronous method of one instance, no other thread can enter any one of the synchronization methods for that instance.


2) When a thread enters a static synchronization method for a class, no other thread can enter any of the static synchronization methods for that class.


Attention:


    1. There is no relationship between a synchronous static method and a non-static method. The static synchronous method and the non-static synchronization method can be executed concurrently, unless the non-static synchronization method explicitly synchronizes on the class (for example, synchronized (Myclass.class) {...} )

    2. The constructors of a class cannot be defined as synchronous.


Monitor or internal lock


Locks restrict access to an object's state, while guaranteeing a happens-before relationship.


Each object has a lock object, and a thread must request a lock before accessing the object and releasing the lock after completion. Other threads cannot access the object and know the lock that gets the object. This ensures that a thread changes the state of the object after the new state is visible to the other on the same monitor's thread.


When a thread releases a lock, the contents of the cache are updated to main memory, which makes the object's state changes visible to other threads-this is the happens-before relationship.


Synchronized and volatile, including the Thread.Start () and Thread.Join () methods, can guarantee happens-before relationships.


A synchronization statement acquires the same lock as a synchronous method, and a thread can request the same lock multiple times.


Once a thread has acquired an object lock, it does not affect the other threads accessing the object's fields or calling the object's non-synchronous methods.


The synchronization statement first attempts to get the lock on the object, gets the synchronization code block immediately after the success, and then releases the lock when the execution is complete.


If the method is an object member or an object instance, the thread locks the instance. If the method is static, the thread locks the class object that corresponds to it. The synchronization method is marked with a synchronized token, which is identified by the method invocation directive.


Atomic variables


See statement int C + +, which contains multiple operations, e.g. reads the value of C from memory, adds a value of C to 1, and then writes back to memory. This operation is correct for a single thread, but it can be wrong in a multithreaded environment. It has a race condition in which multiple threads may read the value of C simultaneously in a multithreaded environment


Atomic access guarantees that all operations are completed once as a whole. An atomic operation is either completely executed or not executed at all.


The following actions can be considered atomic operations:


    1. Read and write operations on reference types and most basic data types, except for long and double types.

    2. Read and write operations that are declared as volatile type variables (including long and double variables).


Java and contract java.util.concurrent.atomic defines a class that atomically operates on a single variable. All classes have get and set methods, just like reading and writing to volatile variables. This means that a write operation Happens-before any other read operation on the variable. Atomic methods Compareandset also have these properties, as do the arithmetic operations of atoms on integer variables.


In Java 5.0 concurrent packages, classes that support atomic operations are defined. Java virtual machines compile these classes with the CAS (Compare and set) provided by the hardware.


    • Atomicinteger

    • Atomiclong

    • Atomicboolean

    • Atomicreference


Volatile variable


Volatile can only be used to modify variables. Variables modified with volatile may be modified asynchronously, so the compiler will treat them in a special way.


The volatile modifier guarantees that any thread that reads a field can see the value that the variable was recently written to.


Variables that use volatile modifiers reduce the risk of memory consistency because any write to a volatile variable can be visible to other threads. In addition, when a thread accesses a volatile variable, it can not only see the most recent modification to the variable, but also modify the other effects of the variable's code.


In a multithreaded environment, objects have replicas stored in different threads. But the volatile variables are not, they have only one instance in the heap. This changes the volatile variable to be immediately visible to other threads. Additionally, the local thread cache does not work when the refresh is completed.


Volatile can guarantee visibility, but it also brings a race condition. It does not lock and wait for an action to complete. For example:


volatile int i=0;


When two threads execute the i +=5, a value between 5-10 is obtained (translator Note: The original is I +=5 invoking by two simultaneously thread give result 5 or ten but it guarantee to See immediate changes feeling a problem)


usage Scenario : A volatile Boolean variable is used as a flag for terminating a thread.


The difference between static and volatile variables


Declaring a static variable means that multiple instances of the class will share the variable, and the static variable is associated with the class instead of the object. Threads may have local cache values for static variables.


When two threads update the value of a static (non-volatile) variable at the same time, there may be an expired value in the cache of one thread. Although multiple threads can access the same static variable, each thread may still save its own cached copy.


A volatile variable retains only one copy in memory, which is shared across multiple threads.


The difference between volatile variables and synchronization


Between the thread memory and the main memory, volatile just synchronizes the value of a variable, synchronized synchronizes the values of all variables (in the synchronized block), and locks and releases a monitor. So, synchronized has more overhead than volatile.


A volatile variable does not allow a local copy to be different from the value in main memory. A variable that is declared volatile must ensure that replicas in all threads are synchronized, regardless of which thread modifies the value of the variable, and that the value is immediately visible to other threads.


Lock Object


The lock object acts like an implicit lock used by the synchronized code. Like an implicit lock, only one thread can hold a lock at the same time. Locks also support the wait/notify mechanism through the condition objects between them.


The advantage of locking objects relative to implicitly locks is that they can be returned from the state in which they are trying to acquire a lock. The Trylock () method can return if the lock is currently unavailable or before a time-out. The lockinterruptibly () method can be returned if another thread sends an interrupt before the lock is acquired.


Java Memory Recycling


In Java, the objects that are created are stored in the heap. The Java heap is called the memory-reclaim heap. Memory collection cannot be enforced. When the memory collector is running, it frees up memory that the unreachable objects occupy. The garbage collection thread runs as a low-priority daemon thread. You can prompt a virtual machine for garbage collection through System.GC (), but you cannot force it to execute.


How to write a deadlock program


In a multithreaded environment, deadlocks mean that two or more threads are blocking and waiting for other threads to release the lock. Here is an example of a deadlock:


public class Deadlocksample {

Private Final Object obj1 = new Object ();

Private Final Object obj2 = new Object ();

public static void Main (string[] args) {

Deadlocksample test = new Deadlocksample ();

Test.testdeadlock ();

}

private void Testdeadlock () {

thread T1 = new Thread (new Runnable () {

public void Run () {

CalLock12 ();

}

});

Thread t2 = new Thread (new Runnable () {

public void Run () {

CalLock21 ();

}

});

T1.start ();

T2.start ();

}

private void calLock12 () {

Synchronized (obj1) {

Sleep ();

Synchronized (OBJ2) {

Sleep ();

}

}

}

private void CalLock21 () {

Synchronized (OBJ2) {

Sleep ();

Synchronized (obj1) {

Sleep ();

}

}

}

private void sleep () {

try {

Thread.Sleep (100);

} catch (Interruptedexception e) {

E.printstacktrace ();

}

}

}


Reference types in Java


The JAVA.LANG.REF package can be used to declare soft references (soft reference), weak references (weak reference), and virtual references (phantom Reference).


    • The garbage collector does not reclaim strong references.

    • Soft references are recycled when there is not enough memory, so using it to implement caching avoids running out of memory.

    • The garbage collector will reclaim weak references at the next garbage collection. Weak references can be used to implement a special map. The key in Java.util.WeakHashMap is a weak reference.

    • Virtual references are immediately recycled. Activities that can be used to track objects being garbage collected.

Sweep
Follow the public number

will open ""Applet Cancel Open

Java Interview Reference Guide-sync

Related Article

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.