Synchronization of threads in Java multithreaded learning

Source: Internet
Author: User
Tags visibility volatile

One of the basic problems to be solved in multithreaded programming is the competition of shared resources. and basically using concurrency mode in solving this problem is to use serialization to access the shared resources method . The rationale is that when a shared resource is used by a task, it locks on it, and other tasks cannot access it until the resource is unlocked. After the task has been unlocked, another task can lock and use it. Here's a look at the thread synchronization mechanism supported by Java.

1.synchronized Keywords

The Synchronized keyword can be applied to object-related synchronization or to class-level synchronization (static property);

Applying synchronized on an object can implement synchronization of object methods and code block synchronization.

Apply the Synchronized form on the object method as:

synchronized void functionname ().

When a synchronized-modified method is called on an object, the object is locked, and the other synchronized methods on the object are called only after the previous method call is complete and the lock is released. A task can get the lock of an object multiple times (for example, inside the synchronized method, the second method that invokes the object, and the third method that invokes the object). When the lock is released, the lock is not actually released until the last synchronized method call is complete. In concurrent programming, it is important to set the domain to private, otherwise the Synchronized keyword cannot prevent other tasks from accessing the domain.

If you want to get a smaller synchronization granularity, you can use synchronized to synchronize part of the code inside the method, in the form of:

Synchronized (SyncObject) {

Inside the curly braces is a block of code to synchronize and also a critical section

}

Before entering the critical section, the lock of the SyncObject object must be obtained, and it is most reasonable to use the method called object as syncobject:synchronized (this). Compared to synchronizing the entire method, the synchronization control block performs better because the object is not locked for a longer period of time.

Use synchronized to decorate the static method to prevent access to static data within the class scope.

When do you want to synchronize? Synchronization rule: When you are writing a variable, he may be read by another thread, or reading a variable that has already been written by another thread, you must use synchronization, and the read-write thread must be synchronized with the same monitor lock. It's called Brian's sync rule.

2. Atomicity and variability

An atomic operation is an operation that cannot be interrupted by a thread-scheduling mechanism, and once the operation is started, it must be completed before a possible "context switch" (switching to another thread) can take place. Java built-in basic types, except for the 64-bit long and double, read and write operations are atomic. Because the JVM separates 64-bit read and write operations into two 32-bit operations, this process can lead to thread switching. To get a long or double atomic operation, use the volatile keyword. Atomic operations are threaded to ensure that they are non-disruptive and can be used to write unlocked code (however, it is not recommended to use atomic actions instead of synchronization). Note in Java, increment and decrement operations (++/--) are not atomic operations .

Visibility issues: in multi-core operating systems, changes made to a task, even atomic, may be invisible to other tasks (modifications are only temporarily stored on the local processor's cache). But the synchronization mechanism forces a task to make modifications that must be visible in the app. The volatile keyword can also provide visibility guarantees. If you declare a field (field) as volatile, all read operations can see this modification as long as a write is generated for the field.

  Note the difference between atomicity and visibility: Atomic operations in non-volatile domains do not have to be flushed into main memory, so other tasks that read the domain do not have to see this new value. Atomicity does not represent and does not ensure visibility.

Usage principle: If a domain may be accessed concurrently by multiple tasks, or at least one of these tasks is a write task, the domain should be set to volatile.

3. Using an explicit lock object

Java SE5 A new explicit mutex mechanism. The lock object must be explicitly created, locked, and disposed. For example:

public class Locktest {

private int currentval = 0;

Private lock lock = new Reentrantlock ();

public int timed () {
Boolean locked = FALSE;
try {
System.out.println ("timed ...");
Locked = Lock.trylock (2, timeunit.seconds);
++currentval;
return currentval;
}
catch (Interruptedexception e) {
E.printstacktrace (System.out);
return-1;
}
finally {
if (locked)
Lock.unlock ();
System.out.println ("Finish timed ... locked=" +locked);
System.out.println ("currentval=" +currentval);
}
}

public static void Main (string[] args) throws exception{
Executorservice Executorservice = Executors.newcachedthreadpool ();
Final Locktest SyncObject = new Locktest ();
Executorservice.execute (New Runnable () {

public void Run () {
try {
Syncobject.nextint ();
}catch (Exception e) {
E.printstacktrace (System.out);
}
}
});
Executorservice.execute (New Runnable () {

public void Run () {
Syncobject.timed ();
}
});
Executorservice.shutdown ();
}

}
Output:

Nextint ....
Timed ....
Finish timed .... locked=false
Currentval=1
Finish Nextint ....
currentval=2

Using a timed acquisition lock operation, the lock object is not acquired within the specified time, and the program is executed as usual, resulting in a different step. The better implementation is: 1. After attempting to acquire a lock timeout, try again; 2. Report timeout as returned.

Synchronization of threads in Java multithreaded learning

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.