This article will be elaborated from two aspects:
Use the C + + language to describe the Monitor Object design pattern. Java has done a very good job of language encapsulation of such a typical pattern, so for Java developers, a lot of things about the pattern itself have been blocked off. This article attempts to use the Native C + + language to help readers to have a more comprehensive understanding of the Monitor object design pattern in essence.
Combined with the C + + version of the Monitor Object design pattern, the reader is guided to a deeper understanding of the Java synchronization mechanism, helping readers to use the Java synchronization mechanism correctly and effectively.
Preliminary knowledge
Before you start a formal discussion, you need to know some preliminary knowledge.
What is RAII
Resource acquisition is initialized (RAII, Resource acquisition is initialization) to obtain a resource in the constructor of an object and to release it in the destructor of that object. This resource can be an object, memory, file handle, or other type. A class that implements this functionality, we say it takes the form of resource acquisition, which is initialized (RAII). RAII is a typical language idiom that is used by many OO languages, and the following are examples of C + +.
Listing 1. RAII Using C + +
class Raii {
public:
// Store a pointer to the resource and initialize the resource.
Raii(Resource &resource)
:m_pRes (&resource){
m_pRes->initialize ();
}
// Close the resource when the execution goes out of scope.
virtual ~Raii() {
m_pRes->close ();
}
private:
// Pointer to the resource we're managing.
Resource *m_pRes;
// ... maybe need disallow copying and assignment ...
};
The advantage of using RAII is that because destructors are automatically invoked by the system, this helps us automatically implicitly release the resources we acquire. Things, we know a lot of C + + technology used in this design pattern, such as: smart pointer, and we will discuss the scope of the lock (Scoped lock).
Unlike the C++,java object, which has no destructor, the Java System provides a GC to manage memory resources. For resources such as database connectivity, Sockets, Java provides finalize () processing. Note, however, that the Java finalizer is different from the C + + destructor, and the Finalize () function is invoked asynchronously at some appropriate time by the GC, and we cannot use Finalize () to implement the RAII in C + +. The usual practice is to use the finally-provided block of the Java-supplied statement.
Listing 2. RAII Using Java
MyResource res = null;
try {
res = new MyResource();
// Use the resource
} finally {
//At exit point, close the resource.
if (res != null) { res.close(); }
}