Example for singleton pattern
Describe a class in the JDK that uses the Singleton design pattern
I am sorry............... could you please explain a
class in JDK which follews singleton pattern?
I was asked this question in an interview yesterday?See reply #2 for a fine example of a potential Singleton object.
kind regards,
Jos
Similar Messages
-
Hi All,
Can anybody give me an simple, pratical example and a sample code to understand prototype pattern.
I need a simple example with code.
Thanks,
J.Kathirpublic interface Prototype {
public void someFunction();
public Object clone();
public class Foo {
private Prototype p;
public static void main(String[] args) {
p = new SomePrototype();
Prototype x = (Prototype)p.clone();
x.someFunction();
p = new SomeOtherPrototype();
x = (Prototype)p.clone();
x.someFunction();
} -
Candidates for use of Singleton Pattern
Hi
Can any guide me , where to use Single Design pattern in Java Based Applications
Should i use Singleton Pattern in the following situations
1)RMI Server
2)Controller Classes ( MVC) invoked by Servlet
3)Database cashing /handling classes
Please suggest other suitable places also
Thanks in AdvanceHii
Typical uses of a singleton pattern are in those cases where you have to have a single instance of a class.For example if u have an RMI based application and the client needs to perform a RMI lookup(for the URL etc)in that case for a particular user you wud like to have just a single instance for the lookup.
In case of controller classes invoked by the servlet you would typically not want a Singleton as multiple instances of the servlet might require to use a controller object.As the request parameters would be different for each servlet instance,you would need a controller object for each of them. -
Code for singleton design pattern
Hi,
This is kalyan. Can u provide code for Singleton design pattern.
Thanks in Advancepublic class Singleton {
private Singleton() {
private static Singleton instance;
public Singleton getSingleton() {
if (instance == null) instance = net Singleton();
return instance;
}Does it make sense? -
Do I need a Singleton pattern for this case
Hello,
I'm writing a game in Java and I have a very simple score manager class which just tracks the points the player so far has. I need to access this class in different pars of my app (gui, game core ...) so I created a singleton class which looks like this
public class ScoreManager {
private static ScoreManager instance = new ScoreManager();
private int score = 0;
private int highScore = 0;
public static ScoreManager getInstance() {
return instance;
public int getScore() {
return score;
public int getHighScore() {
return highScore;
public void addScore(int scoreToAdd){
score += scoreToAdd;
if(score > highScore) {
highScore = score;
}so far so good ..
I would like to read the "highScore" from a file when the game starts and write it back when the game ends. I added those two methods:
public void init(File highScoreFile) {
highScore = readFromFile(highScoreFile);
score = 0;
public void dispose(File highScoreFile) {
writeToFile(highScoreFile);
}So basically I call the init() method when the game stars and the dispose() when the game ends.
It works but what I don't like is that the init() and dispose() methods are exposed and someone could call them in a wrong place.
What would be a better way to do this ?
Thanks for your help,
Jessesafarmer wrote:
You could keep track of the state (initialised, destroyed etc) in the manager and only perform the action if it is an expected state.
private enum State { NOT_INITIALISED, INITIALISED, DESTROYED};
private State currentState = State.NOT_INITIALISED;
// i will leave the rest up to your imagination :) this looks good, thanks
anotherAikman wrote:
>
It works but what I don't like is that the init() and dispose() methods are exposed and someone could call them in a wrong place. And who would that be? You´re the only one using the code, aren´t you?
If not, you could still include in the documentation where to call those methods.
no I'm not the only one working on this. Documentation can be useful but does not prevent calling wrong methods.
YoungWinston wrote:
I don't see any constructor. Usually, a singleton class should have a private one, even if it has no parameters. If you don't have any, Java will create a public no-parameter one as default.ok I forgot the private constructor.
It works but what I don't like is that the init() and dispose() methods are exposed and someone could call them in a wrong place. Then my advice would be not to make them public. After all, your code is the only one calling these methods - yes?yes only the code of the app calls it.
If you are convinced that your game requires one and only one score manager, then a singleton is probably the best way to go.
I'm a little worried about the init() and dispose() methods though, because these suggest state changes, which is unusual for the singleton pattern. You may want to think about synchronizing them.
An alternative might be to use properties to get and store your scores.ok for the synchronization. What would using the properties ? It would be just another type of storage backend and I'd still need to read/write it.
Thanks for your help,
J -
Examples for all service patterns and communication patterns.
Hi Friends,
Can anyone of you give me some real life examples for follwoing service/communication patterns?
1)Synchronous
2)Asynchronous
3)Request Confirmation
4)ReadQuery
5)Notification
6)Information
And also if any guidelined on when to use which patter etc...
Thanks in advance,
Best Regards,
UjwalHi,
Suggestion is to refer SAP help for details:
1)Synchronous: when you need realtime response, i.e. you accept order and want to give order number to customer then you will call Sync service.
2)Asynchronous: when you dont need realtime response, i.e. you want to replicate all orders from one system to another system.
3)Request Confirmation: you made a request and system confirm your request. i.e. Order data is supplied and order number is confirmation. Database will be updated.
4)ReadQuery: I guess you are refering to Query/Response pattern, You just want some information. No database will be updated.
5)Notification: It is another form of "QueryResponse" but user action required.
6)Information: It is another form of "QueryRespone" but NO user action required.
Answer following questions to determine which pattern you need.
Q1. Do you need response?
Ans: Yes: Sync pattern
Q1.1: Does any update required?
Ans: Yes: RequestConfirmation pattern.
Ans: No: QueryResponse pattern.
Ans: No
Q1.2 Does user required to take notice of response?
Ans: Yes:Notification pattern
Ans: No: Information pattern.
Regards,
Gourav
Edited by: Gourav Khare on Jul 27, 2009 2:18 PM -
Implementing Singleton Pattern in ESB
How do I go about implementing a singleton pattern within the ESB. Example usage would be for a cache. Prior to making an expensive service call I want to make sure that the data does not already exist within the cache.
Have a look at metalink note 746108.1
cheers
James -
Singleton pattern class and static class
Hi,
what is difference between the singleton pattern class and static class ?
in singleton pattern, we declare a static member[which hold one value at a time] ,static method[ which return static member value] and a private constructor[not allow to direct instantiation]. My words are -- as a singleton pattern we implement static class .
so can we say a singleton pattern is static class it means both are same or is any difference between these two ??malcolmmc wrote:
On several occasions I've had to convert a static (never instanceated) class to a singleton type, for example because I realise I need an instance per thread, or I decide to make a program more modular, with more than one configuration.
I've never done the opposite.
So generally I favour the singleton if there any "state" involved, because it's more flexible in unanticipated directions. It also gives extra flexibility when building tests, especially if you program to an interface.Total agreement; if anything it is dead hard to override static method logic with mock code in unit tests (I had to do it by keeping the static methods in place but making them internally use a singleton instance of itself of which the instance variable could be overwritten with a mock implementation for unit testing purposes...).
'Static classes' and/or methods are great for very simple util functions, but I wouldn't use them for anything other than that. -
Singleton pattern, scheduled receive location and suspended orchestrations
Hello,
In our project we have several orchestrations that are triggered every minute with the Scheduler Adapter (business requirement is near real-time).
Each of these orchestration must have only 1 instance running at the same time, so we have implemented the singleton pattern. We followed a design like this one: https://fehlberg.wordpress.com/2008/06/06/biztalk-singleton-orchestration-design/
But we end up having suspended orchestrations with the error "The instance completed without consuming all of its messages. The instance and its unconsumed messages have been suspended."
I know it's a risk with this pattern. I thought it would happen only when the instance would run in more than 1 min (because the scheduler adapter is sending a file every minute).
But it happens even with some instances running in about 15sec, so there is something I don't understand, here is an example:
Here we can see that the TransferRegion orchestration started at 10:26:00 (which is expected) and failed.
When I open the orchestration debugger, the time is different, the orchestration is shown starting at 10:26:44 (44 sec later):
And the orchestration ended at 10:27:00:453.
The message not consumed that caused the error has been triggered at 10:27:00.
So I understand that the message arrived just after the listen shape but before the orchestration ends, but I don't understand why the orchestration started 44 sec after is was supposed to ...
Any idea? I'm kind of clueless for now ...So, are these 8 Orchestrations actually processing messages or are they doing some other work every minute or so?
If they're not processing actual messages, maybe a Windows Service or job scheduled by the SQL Agent or Windows Scheduler would be more...appropriate. We all love BizTalk, but some parts of the stack do some things better.
If they are processing messages or doing some genuine BPI type work, calling services, transformations etc., then maybe a Singleton+Scheduled Task is not the best solution.
I'm assuming the actual requirement is the process must run with no less than 1 minute between executions, but if an execution takes >1 min, don't overlap. An internal 1 min timer would probably work very well, but you still have the problem of
activating and deactivating the Orchestration. You'd basically have to build some control infrastructure similar to the EDI Batching Service.
Here's a completely different suggestion:
SQL Table that maintains the state of each process, say Active or Complete.
Poll every 15 seconds a Stored Procedure that tests the status and returns an activation message when that process shows Complete. It would flip it to Active at the same time.
Orchestration runs and the last shape sends a message to change the status to Complete.
Rinse Repeat. No long running Orchestrations, Singletons, Correlations, etc...
Hi John,
We have 8 independent orchestrations. Each of them is triggered by different scheduled receive location.
The orchestrations then process messages (calling stored procedures, mapping and calling web services).
You are right for the requirement. I tried to deactivate the receive location at the beginning of the process and restart it at the end, but I ran into some weird errors on the SSO DB and others like "Could not retrieve transport type data for Receive
Location 'Trigger_xxxxx_SCHEDULE' from config store. The transaction associated with the current connection has completed but has not been disposed. The transaction must be disposed before the connection can be used to execute SQL statements."
Thanks for the new design suggestion, I will see the effort required and if the client approves it ;) -
How can I use SQL to search for a pattern within a field?
Hello, Frank, Solomon, ect
I am now faced with this particular scenario, I've got the SQL to search through a field to find text within the field, but I have to know what it is before it can look for it.
What I have to do is this:
Search through a field, for a pattern, and I won't know what the data is I am looking for. Can this be done in SQL?
For instance, Here is my SQL this far, I was helped allot in order to get to this point.
select table_name,
column_name,
:search_string search_string,
result
from (select column_name,
table_name,
'ora:view("' || table_name || '")/ROW/' || column_name || '[ora:contains(text(),"%' || :search_string || '%") > 0]' str
from cols
where table_name in ('TABLE1', 'TABLE2')),
xmltable (str columns result varchar2(10) path '.')
When you execute the above SQL, you have to pass in a value. What I really need is to alter the above SQL, to make it search for a pattern that exist's within the text of the field itself.
Like for instance, lets say the pattern I am looking for is this" xx-xxxxx-xxxx" and it's somewhere in a field.
I need to alter this SQL to take this pattern and search through all the schemas and tables to look for this pattern match.
Can be done?When you use something dynamically within a function or procedure, roles do not apply and privileges must be granted directly. So, you need to grant select on dba_tab_cols directly. If you want to do pattern matching then you should use regular expressions. The following example grants the proper privileges and uses regexp_instr to find all values containing the pattern xxx-xxxx-xxxx, where /S is used for any non-space character. I limited the tables in order to save time and output for the test, but you can eliminate that where clause.
SYS@orcl> CREATE USER test IDENTIFIED BY test
2 /
User created.
SYS@orcl> ALTER USER test QUOTA UNLIMITED ON USERS
2 /
User altered.
SYS@orcl> GRANT CREATE SESSION, CREATE TABLE TO test
2 /
Grant succeeded.
SYS@orcl> GRANT SELECT ON dba_tab_cols TO test
2 /
Grant succeeded.
SYS@orcl> CONNECT test/test
Connected.
TEST@orcl> SET LINESIZE 90
TEST@orcl> CREATE TABLE table1
2 (tab1_col1 VARCHAR2(60))
3 /
Table created.
TEST@orcl> INSERT ALL
2 INTO table1 (tab1_col1) VALUES ('xxx-xxxx-xxxx')
3 INTO table1 (tab1_col1) VALUES ('matching abc-defg-hijk data')
4 INTO table1 (tab1_col1) VALUES ('other data')
5 SELECT * FROM DUAL
6 /
3 rows created.
TEST@orcl> CREATE TABLE table2
2 (tab2_col2 VARCHAR2(30))
3 /
Table created.
TEST@orcl> INSERT ALL
2 INTO table2 (tab2_col2) VALUES ('this BCD-EFGH-IJKL too')
3 INTO table2 (tab2_col2) VALUES ('something else')
4 SELECT * FROM DUAL
5 /
2 rows created.
TEST@orcl> VAR search_string VARCHAR2(24)
TEST@orcl> EXEC :search_string := '\S\S\S-\S\S\S\S-\S\S\S\S'
PL/SQL procedure successfully completed.
TEST@orcl> COLUMN "Searchword" FORMAT A24
TEST@orcl> COLUMN "Table" FORMAT A6
TEST@orcl> COLUMN "Column/Value" FORMAT A50
TEST@orcl> SELECT DISTINCT SUBSTR (:search_string, 1, 24) "Searchword",
2 SUBSTR (table_name, 1, 14) "Table",
3 SUBSTR (t.column_value.getstringval (), 1, 50) "Column/Value"
4 FROM dba_tab_cols,
5 TABLE
6 (XMLSEQUENCE
7 (DBMS_XMLGEN.GETXMLTYPE
8 ( 'SELECT ' || column_name ||
9 ' FROM ' || table_name ||
10 ' WHERE REGEXP_INSTR
11 (UPPER (' || column_name || '),''' ||
12 UPPER (:search_string) || ''') > 0'
13 ).extract ('ROWSET/ROW/*'))) t
14 WHERE table_name IN ('TABLE1', 'TABLE2')
15 ORDER BY "Table"
16 /
Searchword Table Column/Value
\S\S\S-\S\S\S\S-\S\S\S\S TABLE1 <TAB1_COL1>matching abc-defg-hijk data</TAB1_COL1>
\S\S\S-\S\S\S\S-\S\S\S\S TABLE1 <TAB1_COL1>xxx-xxxx-xxxx</TAB1_COL1>
\S\S\S-\S\S\S\S-\S\S\S\S TABLE2 <TAB2_COL2>this BCD-EFGH-IJKL too</TAB2_COL2>
3 rows selected. -
I want to search for a pattern string in the entire registry and need to delete all the keys and sub-keys that contain the pattern. How can I implement this in VB Script or C#? Appreciate if you can give some sample examples. Now every time, I am manually
searching for the pattern in registry and deleting one by one.
Thanks PrasadThere is no built in way to do this. You'll end up having to enumerate all keys and values in the entire registry and comparing each one for a pattern using Regex or similar. This is going to be really slow but there isn't much else you can do about
it (other than parallelize the enumeration). Also note that you won't have permissions to all keys for read and/or write access so you'll need to skip over those using exception handling.
Michael Taylor
http://blogs.msmvps.com/p3net -
Use of Singleton pattern in Distributed environment
Can somebody say why it is not advisable to use Singleton pattern for developing client server applications.
Client-server does not imply distributed environment, IMHO. There are pretty simple C/S architectures where Singleton pattern is not generally a bad thing.
Distributed environments usually have multiple VMs running, while the singleton pattern typically implemented is a per-VM singleton. -
Serializing a class that implements the Singleton pattern
Hello,
I am relatively new to Java and especially to serialization so the answer to this question might be obvious, but I could not make it work event though I have read the documentation and the article "Using XML Encoder" that was linked from the documentation.
I have a class that implements the singleton pattern. It's definition is as follows:
public class JCOption implements Serializable {
private int x = 1;
private static JCOption option = new JCOption();
private JCOption() {}
public static JCOption getOption() { return option; }
public int getX() { return x; }
public void setX(int x) { this.x = x; }
public static void main(String args[]) throws IOException {
JCOption opt = JCOption.getOption();
opt.setX(10);
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Test.xml")));
encoder.setPersistenceDelegate(opt.getClass(), new JCOptionPersistenceDelegate());
encoder.writeObject(opt);
encoder.close();
}Since this class does not fully comply to the JavaBeans conventions by not having a public no-argument constructor, I have create a class JCOptionPersistenceDelegate that extends the PersistenceDelegate. The implementation of the instantiate method is as follows:
protected Expression instantiate(Object oldInstance, Encoder out) {
Expression expression = new Expression(oldInstance, oldInstance.getClass(), "getOption", new Object[]{});
return expression;
}The problem is that the resulting XML file only contains the following lines:
<java version="1.5.0_06" class="java.beans.XMLDecoder">
<object class="JCOption" property="option"/>
</java> so there is no trace of the property x.
Thank you in advance for your answers.How about this:
import java.beans.DefaultPersistenceDelegate;
import java.beans.Encoder;
import java.beans.Expression;
import java.beans.Statement;
import java.beans.XMLEncoder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class JCOption {
private int x = 1;
private static JCOption option = new JCOption();
private JCOption() {}
public static JCOption getOption() { return option; }
public int getX() { return x; }
public void setX(int x) { this.x = x; }
public static void main(String args[]) throws IOException {
JCOption opt = JCOption.getOption();
opt.setX(10);
ByteArrayOutputStream os = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder( os );
encoder.setPersistenceDelegate( opt.getClass(), new JCOptionPersistenceDelegate() );
encoder.writeObject(opt);
encoder.close();
System.out.println( os.toString() );
class JCOptionPersistenceDelegate extends DefaultPersistenceDelegate {
protected Expression instantiate(Object oldInstance, Encoder out) {
return new Expression(
oldInstance,
oldInstance.getClass(),
"getOption",
new Object[]{} );
protected void initialize( Class<?> type, Object oldInstance, Object newInstance, Encoder out ) {
super.initialize( type, oldInstance, newInstance, out );
JCOption q = (JCOption)oldInstance;
out.writeStatement( new Statement( oldInstance, "setX", new Object[] { q.getX() } ) );
} Output:
<?xml version="1.0" encoding="UTF-8"?>
<java version="1.5.0_06" class="java.beans.XMLDecoder">
<object class="JCOption" property="option">
<void property="x">
<int>10</int>
</void>
</object>
</java> -
Per Web Application singleton pattern
Hello
I have a application (ear) file that look something like this:
App.ear
-- Web_1.war
----- WEB-INF/lib/helper.jar
-- Web_2.war
----- WEB-INF/lib/helper.jar
-- Web_3.war
----- WEB-INF/lib/helper.jar
inside helper.jar there is a singleton class., which get initialised differently depending on which Web_<X> it is loaded in. This currently works because each lib directory get loaded by each own classloader.
I would really like to move the helper.jar up to the <ear file>/lib directory, but that means it is only loaded by the classloaders once anf thus the 3 singletons break as there is now only one.
I would like to have some sort of "Per Web application" globally reachable "singleton".
I have thought about using ServletContext, but it appears that there is no easy ways for helper classes to look it up, unless it is passed as a parameter.
A second idea would be to use ThreadLocals, but that would rely on the Web container not reusing threads accross web applications. I am not sure if this is guranteed not to happen ...
In any case, what is the best way to handle this ? is there any standard way or a design pattern to follow...I suppose another way of asking this question is this:
is there a way to use the singleton pattern on a
per-web-application basis without storing the
singleton in the ServletContext? If I can find a way
to do that, I can solve my initial problem.Some web application servers run each webapp in a separate JVM, or at least a separate classloader. If yours does either of those, then each webapp will have its own instance of the singleton. Try it. -
if i use Class.forName(MyClass).newInstance() to init MyClass and MyClass uses singleton pattern, i wonder what is the difference between Class.forName(MyClass).newInstance() and Class.forName(MyClass).newInstance().getInstance(),i meant whether the former object is singleton or not(plz tell me why). or i should never let sth like this happen(i should not use both Class and singleton,plz tell me the reason 2) or is there any other pattern than can combine both of them.
any discussion will be appreciated.thanx in advance
Ciao,
zhxthi scratchback,
are you sure that MyClass uses singleton pattern? I haven't tried Class.forName(MyClass).newInstance() in a singleton class before, but I don't think it will work if your constructor is private.
singleton pattern is used for classes that you think should exist in the application only once.
hope it helps..
ronron
Maybe you are looking for
-
How do I download DVDs into my itunes for my iPad
How do I download DVDs into my iTunes for my iPad?
-
When I insert my CD it is not opening up in itunes
when I insert my CD it is not opening up in itunes
-
Is there any way to get rid of the white space around an image. A lasso?
-
I am going to buy a second Apple TV. When I turn on Apple TV with the Remote App, will it activate both Apple TV boxes or will it allow me to select the one I want to operate?
-
Any ideas why I get this fail when opening iTunes?? fail -42032