Valid Java note (12)

Source: Internet
Author: User

List of related Reading Notes

No. 48 synchronous access to shared variable data

Synchronization not only prevents a thread from seeing objects in an inconsistent state, but also ensures a series of state transition sequences through a series of seemingly sequential executions, objects change from one consistent state to another consistent state.

The synchronized keyword ensures that at the same time, only one thread is executing a statement or a code block. The Java language ensures that reading or writing a variable is atomic unless the variable type is long or double.

The memory model of Java determines that it is necessary to read and write atomic data for reliable communication between threads and mutex access. Let's look at a terrible example:
// Broken-require synchronization! <Br/> Private Static int nextserialnumber = 0; <br/> Public static int generateserialnumber () {<br/> return nextserialnumber ++; <br/>}

To improve it, you only need to add the synchronized modifier in the generateserialnumber statement.

To terminate a thread, we recommend that the thread poll a domain. If the value of this field changes, it indicates that the thread should terminate itself. The following example shows how to synchronize data.
// Broken-requires synchronization <br/> public class stoppablethread extends thread {<br/> private Boolean stoprequested = false; <br/> Public void run () {<br/> Boolean done = false; <br/> while (! Stoprequested &&! Done) {<br/>... // do what needs to be done in the thread <br/>}< br/> Public void requeststop () {<br/> stoprequested = true; <br/>}< br/>}

The improvements are as follows:
// Properly synchronized cooperative thread temination <br/> public class stoppablethread extends thread {<br/> private Boolean stoprequested = false; <br/> Public void run () {<br/> Boolean done = false; <br/> while (! Stoprequested ()&&! Done) {<br/>... // do what needs to be done in the thread <br/>}< br/> Public synchronized void requeststop () {<br/> stoprequested = true; <br/>}< br/> private synchronized Boolean stoprequested () {<br/> return stoprequested; <br/>}< br/>}

Another improvement is that when stoprequested is declared as volatile, synchronization can be omitted.

Let's look at the lazy initialization problem. The dual access mode may not always work unless the shared variable contains a primitive value. Example:
// The double-check idion fro lazy initialization-broken! <Br/> Private Static Foo = NULL; <br/> Public static Foo getfoo () {<br/> If (FOO = NULL) {<br/> synchronized (FOO. class) {<br/> If (FOO = NULL) Foo = new Foo (); <br/>}< br/> return Foo; <br/>}

The easiest modification is to save the trouble of initialization:
// Normal static initialization (not lazy) <br/> Private Static finall Foo = new Foo (); <br/> Public static Foo getfoo () {<br/> return Foo; <br/>}

Or use the correct synchronization method, but it may increase the synchronization Overhead:
// Properly synchronized lazy initialization <br/> Private Static Foo = NULL; <br/> Public static synchronized Foo getfoo () {<br/> If (FOO = NULL) foo = new Foo (); <br/> return Foo; <br/>}

The On-Demand container initialization mode is also good, but it can only be used for static domains, not instance domains.
// The initialize-on-demand holder class idiom <br/> Private Static class fooholder () {<br/> static final Foo = new Foo (); <br/>}< br/> Public static Foo getfoo () {return fooholder. foo ;}

In short, whenever multiple threads share variable data, each thread that reads or writes data must obtain a lock. If there is no synchronization, the modifications made by one thread cannot be observed by another thread.

No. 51 should not depend on the thread Scheduler

The correctness of applications cannot depend on the thread scheduler. Otherwise, the resulting application is neither robust nor portable. As an inference, do not rely on thread. Yield or thread priority. These facilities only affect the schedulers. They can be used to improve the service quality of a system that can work normally, but they should never be used to "correct" a program that cannot work originally.

The best way to write robust, responsive, and portable multi-threaded applications is to make sure that there are only a few runnable threads at any given moment. The main technique used in this method is to let each thread do a small amount of work, then use object. Wait to wait for a condition to occur, or use thread. sleep for a period of time.

Document-based thread security

Each class should clearly describe its thread security attributes in the document. The synchronized modifier appears in the declaration of a method, which is an implementation detail and is not part of the exported API documentation.

To be safely used by multiple threads, a class must clearly describe the thread security level it supports in the document.

Immutable-instances of this class remain unchanged for other customers and do not require external synchronization. See 13.

Thread-safe (thread-safe)-instances of this class are variable, but all of them contain adequate means of synchronization. These instances can be used concurrently without external synchronization.

Conditional thread-safe-This class (or associated class) contains some methods that must be called sequentially without being disturbed by other threads, in addition, this thread security level is the same as in the previous case. To eliminate the possibility of interference by other threads, the customer must obtain an appropriate lock during the execution of this method sequence. For example, hashtable or vector, their iterators require external synchronization. For example:
Hashtable H = ...; <br/> synchronized (h) {<br/> for (enumeration E = H. keys (); E. hasmoreelements ();) <br/> F (E. nextelement (); <br/>}

Thread-compatible-external synchronization is used on the periphery of each method call. In this case, instances of this class can be safely used concurrently. For example, arraylist or hashmap

The thread-hostile class cannot be safely used by multiple threads concurrently, even if all method calls are surrounded by external synchronization. Generally, the root of the opposition between threads is that static data needs to be modified in this method, which may affect other threads.

For Conditional thread security classes, specify in the document "which object should be locked in order to allow the method call sequence to be executed in an atomic way ".

No. 53 avoid using thread groups

In addition to threads, locks, and monitors, the thread System also provides a basic abstraction, namely thread-group ). However, thread groups do not provide many useful functions.

One exception is that when a thread in the thread group throws an uncaptured exception, the threadgroup. uncaughtexception method is automatically called. The execution environment uses this method to respond to uncaptured exceptions in an appropriate manner.

No. 54 write the readobject method in a protective manner

Writing a readobject method of a class is equivalent to writing a public constructor. No matter what kind of byte stream is passed to it, it must generate a valid instance. The following are the guidelines for the robust readobject method:

① For classes whose object reference fields must be kept private, a protective copy of "objects to be saved in these fields" is performed. The variable components of the non-variable class belong to this category.

② For classes with constraints, check whether the constraints are met. If not, an invalidobjectexception exception is thrown. These checks should follow all protective copies.

③ If the entire object graph must be valid after the object graph is deserialized, use the objectinputvalidation interface.

④ Do not call methods that can be rewritten in the class either directly or indirectly.

⑤ The readresolve method may be used to replace the protective readobject method.

Strictly speaking, readobject is a constructor that uses throttling as a unique parameter. When facing a manually forged byte stream, the object generated by readobject violates the constraints of the class to which it belongs. The initial method is to perform a binding check on the readobject method, as shown in the following example:
Private void readobject (ojbectinputstream s) throws ioexception, classnotfoundexception {<br/> S. defaultreadobject (); <br/> // check that our invariants are satisfied <br/> If (start. compareto (end)> 0) throw new invalidobjectexception (start + "after" + end); <br/>}

The above prevention measures can still be attacked: forge a byte stream, which starts with the byte stream generated by a valid period instance, and then attaches two additional references, points to two internal private date domains in the period instance. Attackers can exploit this vulnerability to attack the internal domain. Therefore, when an object is deserialized, a reference to an object that the customer should not own must be protected if the domain contains such an object reference, this is very important. For example:
Private void readobject (objectinputstream s) throws ioexception, classnotfoundexception {<br/> S. defaultreadobject (); <br/> Start = new date (start. gettime (); <br/> end = new date (end. gettime (); <br/> If (start. compareto (end)> 0) throw new invlaidobjectexception (start + "after" + end); <br/>}

 
No. 57 provide a readresolve method when necessary

Whether it's Singleton or another instance-controlled class, you must use the readresolve method to protect "instance-controlled constraints ". Essentially, the readresovle method converts a readobject method from a real public constructor to a real public static factory. For classes that prohibit non-package inheritance, the readresolve method is also very useful as an alternative to the protective readobject method.

The following sigleton class:
Public class Elvis {<br/> Public static final Elvis instance = new ELVIS (); <br/> private ELVIS () {<br/>... <br/>}< br/>... // remainder omitted <br/>}

If Elvis instance serializes an interface, the following readresolve method is sufficient to ensure its sigleton attribute.
Private object readresolve () throws objectstreamexception {<br/> // return the one true Elvis and let the GC take care of the Elvis impersonator <br/> return instance; <br/>}

Not only are Singleton objects necessary, but the readresolve method is also required for all other instance controlled classes (such as type security enumeration types.

The second usage of the readresolve method is to act as a conservative alternative to the protective readobject method as recommended in article 56th. In this case, the readobject method in Article 1 can be replaced by the following example:
// The defensive readresolve idiom <br/> private object readresolve () throws objectstreamexception () {<br/> return New Period (START, end); <br/>}

For classes that can be inherited, The readresolve method may not be able to replace the protective readobject method. If the readresolve method of the superclass is final, the subclass instance cannot be deserialized normally. If the readresolve method of the superclass is rewritable, the malicious subclass may use a method to rewrite it. This method returns a damaged instance.

 

Conclusion: It took several months to finish reading this book intermittently. During this period, I made several projects and was busy for a while. The reading progress was somewhat delayed, now I have forgotten all the notes I have prepared. But it doesn't matter. I can go back and see it later. Let's learn something new...

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.