Java: only one instance can be started for the same program.
Import java. Io. file;
Import java. Io. randomaccessfile;
Import java. NiO. channels. filechannel;
Import java. NiO. channels. filelock;
Public class singleapplication {
// Call this function in the main method of the application to ensure that only one instance of the program is running.
Public static void makesingle (string singleid ){
Randomaccessfile RAF = NULL;
Filechannel channel = NULL;
Filelock lock = NULL;
Try {
// Create a temporary file in the Temporary Folder and lock the file to ensure that only one instance of the application is created.
File Sf = new file (system. getproperty ("Java. Io. tmpdir") + singleid + ". Single ");
SF. deleteonexit ();
SF. createnewfile ();
RAF = new randomaccessfile (SF, "RW ");
Channel = Raf. getchannel ();
Lock = channel. trylock ();
If (Lock = NULL ){
// If no lock is obtained, the program exits.
// There is no need to manually release the lock and close the stream. When the program exits, they will be closed.
Throw new error ("an instance of the application is running .");
}
} Catch (exception e ){
E. printstacktrace ();
}
}
Public static void main (string [] ARGs) throws exception {
Singleapplication. makesingle ("single. test"); // ensure that only one instance of the program is running.
// Test: simulate a program running for 5 seconds
System. Out. println ("START ");
System. Out. println ("waiting 5 seconds .");
For (INT I = 0; I <5; ++ I ){
Thread. Sleep (1000 );
System. Out. println (I + 1) + "......");
}
System. Out. println ("end ");
}
}
I have found some knowledge about Singleton management, including Java and C ++. I will write it here and I will try to add it later.
Single-state definition:
The Singleton mode ensures that only one instance of a class exists in a Java application. In many operations, such as creating a directory database connection, such single-threaded operations are required.
In addition, Singleton can be stateful. In this way, multiple single-State classes can serve as a status warehouse together. For example, if you want a Post Counter in the Forum, you need to count every time you browse the database. Can single-State classes keep this count and Add 1 to synchronize (synchronous) security? If you want to save this number to the database permanently, you can easily do this without modifying the single-State interface.
In addition, Singleton can also be stateless. Provides tool functions,
The Singleton mode provides us with the possibility of such implementation. Singleton also saves memory because it limits the number of instances and facilitates Java garbage collection ).
We often see that the class loader in the factory mode is also implemented in the singleton mode, because the loaded class actually belongs to resources.
How to use it?
Generally, Singleton mode has several forms:
[Java] view plaincopy
Public class Singleton {
Private Singleton (){}
// Define your own instance internally. Isn't it strange?
// Note that this is private for internal calls only
Private Static Singleton instance = new Singleton ();
// Here is a static method for external access to this class, which can be accessed directly.
Public static Singleton getinstance (){
Return instance;
}
}
Second form:
[Java] view plaincopy
Public class Singleton {
Private Static Singleton instance = NULL;
Public static synchronized Singleton getinstance (){
If (instance = NULL)
Instance = new Singleton ();
Return instance ;}
}
Use singleton. getinstance () to access the single-State class.
The second form above is lazy initialization. That is to say, the initial Singleton will not be regenerated in the first call.
Note that synchronized in the form of lazy Initialization is important. If synchronized is not available, you may obtain multiple Singleton instances by using getinstance. There are many discussions about Singleton of lazy initialization involving double-checked locking (DCL), which will be further studied by interested parties. It is generally considered that the first form is more secure.
Notes for using singleton:
In some cases, Singleton cannot be used for singleton. If multiple Singleton objects are simultaneously loaded by different class loaders; in distributed systems such as ejbs, you should also pay attention to this situation because ejbs are cross-server and cross-JVM.
Take servicelocator of Pet Store source code (Pet Store 1.3.1) of sun as an example to analyze it a little:
In the pet store, servicelocator has two types: one is under the EJB directory and the other is under the web directory. Check the two servicelocator to find that the content is not much different, they all provide the query and positioning service for EJB, but why should they be separated? After careful research on the two servicelocator methods, we can find the difference: servicelocator in the Web adopts the singleton mode, and servicelocator is a resource location. Naturally, we should use the singleton mode. However, in EJB, the singleton mode has no effect, so servicelocator is divided into two types: Web Services and EJB services.
The Singleton mode looks simple and easy to use, but it is not easy to use well. You need to have a good understanding of Java's class thread memory and other concepts.
In short: If your application is based on containers, the singleton mode is rarely used or not used. You can use alternative technologies.
Summary of GEF and EMF plug-in Design Patterns in eclipse
GEF (Graphical Editor framework) is a graphical editing framework that allows developers to visually display and edit models to improve user experience. With GEF, you can easily implement XML editor, UML class diagram editor, and other applications.
EMF (eclipse modelling framework) is an important component of the Model Driven Architecture of eclipse. It can convert models into efficient, correct, and easy-to-Customize Java code.
Based on GEF and EMF, model-driven development (MDD) can be easily implemented. This article combines GEF and EMF plug-ins in graduate design, develop a Graphical Editor plug-in based on object-oriented Petri Net (a Petri Net, a mathematical representation of asynchronous and concurrent computer system models. During this period, I came across some of the design patterns used in these two plug-ins and shared them with you.
1. MVC
GEF uses the MVC framework to eliminate coupling between models and views:
(1) model: It can be expressed by any Java object. The model must have a notification mechanism.
(2) view: Figure/treeitems. In a typical graphicaleditor, figure is the draw2d figure used for display in graphicalviewer, while treeitems is used to display information in the treeviewer in outline.
(3) controller: Usually each figure corresponds to an editpart. editpart is used to control the model and view. Many modification tasks are implemented through editpolicy.
2. Command
Commands in GEF encapsulate modifications to the model. You can inherit the abstract class command in GEF to provide redo/undo functions. We mainly use execute ()/Redo () /undo.
3. chain of responsibility
Chain of responsibility transmits a request to multiple objects and gives these objects the opportunity to process the request, thus decoupling the request sender and receiver. In GEF, multiple editpolicies can receive requests and return commands. These commands are chained together.
In addition, as well as the message distribution mechanism in EMF.
4. State
Allows the Graphical Editor to modify its behavior when its internal status changes. For GEF editor, you can switch the tool to change the editor status. For example, for a mouse-pressed event, the editor performs different operations under the activation selection tool and activation creation tool. For details, see the org. Eclipse. GEF. tool interface. abstracttool defines several States, state_xxx.
5. Abstract Factory
GEF provides interfaces to create a series of related or dependent objects. This mode is used when an editorial component is created based on the model component.
In GEF, different editparts are created based on editpartfactory. In EMF, the factory class modelelementfactory that creates model elements is provided.
6. Factory method
Defines the method to create an object, but allows the subclass to determine the class to be instantiated. This mode is not discussed separately, but it is another optional method for creating an editorial component. The createchild method allows you to create a sub-Editorial component without using the factory.
7. Adapter
The getadapter (class key) method in the editpart of the GEF controller.
The notifier-adapter mechanism of EMF.
8. Singleton
The single plugin instance class abstractuiplugin Of The Eclipse plug-in project ensures that the plug-in is instantiated only once after running.
9. Composite
The composite of each display element in GEF exists in a composite relationship.
In EMF, composite models and submodels are also locked in a composite relationship.
10. Observer
The editpart in GEF is registered to the EMF model object as the observer. It monitors model changes and notifies the view to update the model.
Summary
By using a large number of design patterns, the flexibility and scalability of GEF and EMF plug-ins are achieved, facilitating development.