The Abcs of Synchronization, Part 1 (from www.java.net)

zhaozj2021-02-16  148

By Jeff Friesen 08/02/2004

Threads may execute in a manner where their paths of execution are completely independent of each other. Neither thread depends upon the other for assistance. For example, one thread might execute a print job, while a second thread repaints a window. And then there are threads that require synchronization, the act of serializing access to critical sections of code, at various moments during their executions. For example, say that two threads need to send data packets over a single network connection. Each thread must be able to send its entire data packet before the other thread starts sending its data packet;. otherwise, the data is scrambled This scenario requires each thread to synchronize its access to the code that does the actual data-packet sending.

Correctly synchronizing threads is one of the more challenging thread-related skills for Java developers to master. This article begins a two-part series that attempts to meet that challenge by exploring the fundamentals of Java's synchronization capabilities. It begins by introducing you to the concepts of monitors and locks. you next will learn how synchronized methods and synchronized statements implement those concepts at the language level. Finally, you will learn about deadlock, a nasty problem that often occurs when synchronizing threads.

Note: This series assumes that you have a basic understanding of threads and the java.lang.Thread class, such as how to start a thread Also, keep in mind that the idea of ​​multiple threads simultaneously executing code has slightly different meanings on uniprocessor. and multiprocessor machines. On a uniprocessor machine, threads do not actually run at the same time. The thread scheduler gives the illusion that this is the case. In contrast, where enough processors exist to run all eligible threads, a multiprocessor machine is capable Of actually Running Threads Simultaneously.monitors and Locks

Sun's Java Virtual Machine Specification States That Synchronization Is Based on Monitors. This Point Is Reinforced At The Java VM Level by The Presence of Monitorenter and MonitorExit Instructions.

First suggested by EW Dijkstra in 1971, conceptualized by P. Brinch Hansen in 1972-1973, and refined by CAR Hoare in 1974, a monitor is a concurrency construct that encapsulates data and functionality for allocating and releasing shared resources (such as network connections, memory buffers, printers, and so on). To accomplish resource allocation or release, a thread calls a monitor entry (a special function or procedure that serves as an entry point into a monitor). If there is no other thread executing code within the monitor, the calling thread is allowed to enter the monitor and execute the monitor entry's code. But if a thread is already inside of the monitor, the monitor makes the calling thread wait outside of the monitor until the other thread leaves the monitor. The monitor THEN ALOWS SYNCHRONIZAD. BECAUSE SYNCHRONIZATION IS Guaranteed, Problems Such As Data Being Lost OR Scrambled Area Avoided. To Learn More About Monitors, Study Hoare's Landmark Paper, "" Monitors: An Operating System Structuring Concept, ". First published by the Communications of the Association for Computing Machinery Inc. in 1974.The Java virtual machine specification goes on to state that monitor behavior can be explained in terms of locks Think of a lock as a token that a thread must acquire before a monitor allows that thread to execute inside of a monitor entry. that token is automatically released when the thread exits the monitor, to give another thread an opportunity to get the token and enter the monitor.

Java associates locks with objects: each object is assigned its own lock, and each lock is assigned to one object A thread acquires an object's lock prior to entering the lock-controlled monitor entry, which Java represents at the source code level as either a. synchronized method or a synchronized statement.Note: Java 1.5 introduces the java.util.concurrent.locks package This package includes a Lock interface for implementing locking operations that are more extensive than those offered by synchronized methods and synchronized statements..

Synchronized methods and synchronized statements

A synchronized method is a method that serves as a monitor entry. That method's signature is prefixed with keyword synchronized and the entire method's code is a critical section (a section of code that can be executed by only one thread at a time, to prevent data Loss or corruption). The code Fragment Below Presents a class with two instance-based synchronized methods and one class-based synchronized method:

Public Class SyncMethods

{

Public synchronized void instancethod1 ()

{

// appropriate Method-Related Code.

}

Public synchronized void instanceMethod2 ()

{

// appropriate Method-Related Code.

}

Public Static Synchronized Void ClassMethod ()

{

// appropriate Method-Related Code.

}

}

A SyncMethods Object Reference Is Needed to Invoke Either of the Two Synchronized Instance Methods. For Example:

SyncMethods SM = New SyncMethods ();

Sm.instanceMethod1 ();

The thread that executes sm.instanceMethod1 () needs to acquire the lock associated with the SyncMethods object that sm references before it can enter that monitor entry. If some other thread has that lock, because it is executing code inside of instanceMethod1 () or inside of instanceMethod2 (), the invoking thread is made to wait until the other thread leaves its instance method.Because the static classMethod () does not require an object reference prior to its invocation, which lock does a thread acquire before it can enter that method ? The answer is simple. When a classloader loads a class, the classloader creates a java.lang.Class object that describes the loaded class. A thread acquires the lock from that class object. For example, in SyncMethods.classMethod () ;, The Thread Acquires The Lock from The SyncMethods Class Object.

The lock assigned to a SyncMethods object and the lock assigned to the SyncMethods Class object are two different locks. As a result, one thread may execute inside of either instance method, while a second thread simultaneously executes inside of the class method.

In contrast to the synchronized method, a synchronized statement is a monitor entry with a (usually) smaller critical section. The statement begins with the keyword synchronized, continues with an object identifier placed between a pair of round bracket characters, and concludes with a block Of Statements That Serves as a critical section. The Following Code Fragment Illustrate The Synchronized Statement:

Public Class syncstatements

{

Public void instanceMethod1 ()

{

// setup code.

SYNCHRONIZED (this)

{

// Update file.

}

// Cleanup code.

}

Public void instanceMethod2 ()

{

// setup code.

SYNCHRONIZED (this)

{

// read from file.}

// Cleanup code.

}

}

Let's assume instanceMethod1 () is invoked by a thread that must periodically update a file and instanceMethod2 () is invoked by a different thread whenever it needs to read from that file. In addition to the actual file I / O code, each method contains extensive Setup and cleanup code, Which We'll Assume is Completely Independent of The Other Method's Setup and Cleanup Code. Assumers. Assumers.

Because the setup and cleanup code is independent, the simultaneous execution of both methods 'setup codes or both methods' cleanup codes does not cause data corruption, and synchronization is not required. Since at least part of each method does not need to be synchronized, there is no point in synchronizing the entire method. But threads can not simultaneously update a file and read from that same file. Therefore, each method's appropriate file I / O code is placed within a synchronized statement. When one thread tries to invoke instanceMethod1 () 's update file code, it must first acquire the lock that associates with the current object (that keyword this signifies). Similarly, when the other thread tries invoking instanceMethod2 ()' s read file code, that thread must acquire the same Lock. Only One Thread Will Succeed (if Both Threads Simultaneously Try Acquiring The Lock) and the file will be updated or read from, Depending on Which Thread Obtains the Lock.

Sometimes, it is convenient to use both synchronized methods and synchronized statements in the same code For example, consider a (not necessarily graphical) component's event registration and listener notification logic, as presented by the following code fragment.:

// this code fragment has been Shortened for

// Clarity.

Vector clients = new vector ();

Public Synchronized Void AddClientSlistener

(ClientsListener Cl)

{

Clients.Add (CL);

}

Public Synchronized Void RemoveClientSlistener

(ClientsListener Cl)

{

Clients.Remove (CL);

}

Private void notifyclients ()

{

// ... preamble.

Vector copy;

SYNCHRONIZED (this)

{

CLIENTS.CLONE ();

}

For (INT i = 0; i

// Retrieve Listener Object from Copy

// Vector at index I and fire an event

// Object to That Listener, by Invoking

// a Specific Listener Method with the

// Event Object as an argument to thing

// Method.

}

The code fragment above presents a clients data structure, two synchronized methods for registering and de-registering listener objects (via that data structure), and a private method that incorporates a synchronized statement to assist in notifying those listeners when something interesting happens. Both synchronized methods and the synchronized statement obtain the same lock from the current (this) object The result:. only one thread may execute, at any moment in time, inside of one of the three critical sections.

Why is a synchronized statement used to make a copy of the data structure? To understand the need for that statement, assume the thread that invokes either of the synchronized methods, to register or de-register a client's interest in receiving event notifications, is separate from the thread that invokes notifyClients (). This is often the case in practice. Also, assume that notifyClients () 's synchronized statement was not present and that its for loop worked with clients directly. in that situation, suppose a listener's thread removes the listener from the clients data structure, while the for loop is iterating. At that point, the number of objects in the Vector is less than the number of iterations that the for loop must complete (based on initially evaluating expression i

Large multithreaded programs that involve synchronization can be challenging to write. In addition to making certain that threads do not acquire different locks before entering the same critical section, or related critical sections, the developer must guard against deadlock, a situation where locks are acquired by multiple threads, neither thread holds its own lock but holds the lock needed by some other thread, and neither thread can enter and later exit its critical section to release its held lock because some other thread holds the lock to that critical section. The following Code Fragment Demonstrates this Pathology Scenario for Two Threads:

Public Class Deadlock

{

Private Object lock1 = new object ();

Private Object Lock2 = new object ();

Public void instanceMethod1 ()

{

Synchronized (LOCK1)

{

SYNCHRONIZED (LOCK2) {

// critical section Guarded First By

// Lock1 and dam by Lock2

}

}

}

Public void instanceMethod2 ()

{

SYNCHRONIZED (LOCK2)

{

Synchronized (LOCK1)

{

// critical section Guarded First By

// Lock2 and dam by Lock1

}

}

}

}

Let's assume truth () at Different Times and thread b invokes instanceMethod2 () in The Same Random Fashion. Consider The Following Execution Sequence:

Thread A invokes instanceMethod1 (), obtains the lock assigned to the lock1-referenced object, and enters its outer critical section (but has not yet acquired the lock assigned to the lock2- referenced object). Thread B invokes instanceMethod2 (), obtains the lock assigned to the lock2-referenced object, and enters its outer critical section (but has not yet acquired the lock assigned to the lock1- referenced object). Thread A attempts to acquire the lock associated with lock2. The monitor forces that thread to wait outside of the inner critical section because thread B holds that lock. Thread B attempts to acquire the lock associated with lock1. The monitor forces that thread to wait outside of the inner critical section because thread A holds that lock. Neither thread can proceed because the Other Thread Holds The Needed Lock. We Have A Deadlock Situation and The Program (at Least In The Context of the Two Threads Freezes Up.

Although the previous code fragment clearly identifies a deadlock state, it's often not that easy to detect deadlock. For example, your code may contain a circular relationship among various classes (in several source files), where class A's synchronized method invokes class B's synchronized method , which invokes class C's synchronized method, and so on. Eventually, class Z's synchronized method calls class A's synchronized method. If thread A invokes class A's synchronized method and, while thread A is still inside of that method, thread B invokes class Z's synchronized method, thread B will block when it attempts to invoke class A's synchronized method. Thread A will continue to execute until it invokes class Z's synchronized method, and then block. Deadlock results. This scenario also happens with synchronized statements or a collection of synchronized methods And Synchronized Statements.neither The Java Language Nor The Java VM Provides a Way to Prevent Deadlock. Therefore, Deadloc k prevention is up to the developer The simplest way to prevent deadlock from happening:.. avoid having either a synchronized method or a synchronized statement invoke another synchronized method / statement Although that advice prevents deadlock from happening, it's both impractical (because one of your synchronized methods / statements may need to invoke a synchronized method in a Java API - see the various synchronized methods in the java.util.Hashtable class for examples), and overkill (because the synchronized method / statement being invoked might not invoke any other Synchronized Method / Statement, So Deadlock Wouldn't OCCUR).

NOTE: The ACM HAS Published An Interesting Paper on Extending Java To Support Deadlock Detection.conclusion

Synchronization is one of the more challenging thread-related skills that the successful Java developer must acquire. A solid understanding of monitors and locks, synchronized methods and synchronized statements, and deadlock is your starting point for meeting that challenge.

I Have Some Homework for You To Accomplish:

If a thread holds a lock, what happens when the thread needs to enter another critical section controlled by the same lock? Construct an example that illustrates a lack of synchronization due to a pair of threads acquiring different locks. Use the keyword this and the synchronized statement in the example. in the earlier example of a component's event registration and listener logic, I presented two synchronized methods and a synchronized statement. You might be tempted to remove the synchronized statement from notifyClients () and make the entire method synchronized. What is WRONG WITH THAT IDEA?

Next Month's Java Tech Completes this Series by Exploring Java's Waiting and Notification Mechanism, A Thread Communication Example, Volatile Variables, and Java 1.5's High-Level Synchronization Tools.

Answers to Previous Homework

The Previous Java Tech Article Presented You With Some Challenging Homework On Console-based and GUI-BASED VERSIONS OF THE NIM Computer Game. Let's Revisit That Homework and Investigate Solutions.

Modify ConNim, so that it uses the Scanner class to handle input from the user. Consult the ConNim.java source code in this article's attached code.zip file. GuiNim's onscreen match drag-and-drop logic reveals a quirk. You've selected 1, 2, or 3 onscreen matches while pressing the Shift key, released that key after releasing the mouse button, and noticed that all selected onscreen matches still appear cyan (meaning they are selected). You can deal with the quirk by moving the mouse pointer to a blank area of ​​the screen and then clicking the mouse button, or by releasing the Shift key before releasing the mouse button. Can you think of some better way to handle this quirk? The quirk described above occurs when you drag one or more of the selected matches to the human player's pile of matches and then release the mouse button before releasing the Shift key. This quirk can be handled in a better way by attaching a key listener, which implements the keyReleased method to invoke the mouse listener's mouseReleased method when the Shift key is released, to the GamePanel component in its constructor The following steps accomplish that task:.. Modify GuiNim's constructor so that the GamePanel component requests focus If this is not done, that component can not detect key-release events The Following Code Fragment Shows The Needed Modification:

GamePanel GP = New GamePanel (this);

GetContentPane () .add (gp);

Pack ();

gp.requestfocus (); // this Call Must Come Last.

Change MouseAdapter ma; to final MouseAdapter ma; in GamePanel's constructor This variable must be marked final so it can be accessed from within keyPressed Add the following code fragment after the addMouseListener (ma); method call:.. KeyAdapter ka = new KeyAdapter ()

{

Public void Keyreleased (KeyEvent E)

{

IF (E.GetKeyCode () == Keyevent.vk_shift)

{

MouseEvent ME;

ME = new mouseevent (GamePanel.This,

MouseEvent.mouse_released,

0,

0,

0,

0,

0,

FALSE);

Ma.mouseeleased (me);

}

}

}

AddKeylistener (KA);

When the code fragment detects that Shift has been released, it creates an object from MouseEvent and calls the mouse listener's mouseReleased method with that object as the method's argument. In turn, mouseReleased determines if any selected matches locate over the human player's match pile. If so, the matches are dropped. Otherwise, the matches remain selected. Make the appropriate changes above to GuiNim.java (and also to GuiNim2.java, if desired). Then compile the source code, and run the application. Try dragging matches to THE HUMAN Player's Pile with The Shift Key Held Down. Release That Key Once The Matches Are Over the Pile, And You Should See Them Immediately Disappear.

Jeff Friesen Is A Freelance Software Developer and Educator Specializing In C, C , and Java Technology.

转载请注明原文地址:https://www.9cbs.com/read-7918.html

New Post(0)