Singleton instance inside a doGet() is safe by default?
Reading "Servlets and JavaServer Pages: The J2EE Technology Web Tier" book from Jayson Falker and Kevin Jones page, at page 414, "State and Thread Safety", says that executing a local variable inside a doGet() method is thread safe.
So, can I create a first instance of a singleton class inside a doGet() those this means that the singleton is automatically thread safe and syncronization is not really necesary?
Thanks,
Lorenzo Jim�nez
I am not sure of this, but to make it thread safe, you'd need to synchronize the data access methods in the singleton.
I hope I am wrong and get enlightened.
Regards,
$ Carol.
Similar Messages
-
Instantiate an instance inside its class
I always read codes like following:
Class A {
A a = new A( );
Could anybody tell me why a class is able to instantiate its instance inside itself.
Another example:
Class A {
B b = new B( );
Class B{
A a = new A( )
When Class A is running, it calls Class B, but when Class B is instantiated
, it needs to call Class A. I am always puzzled about this kind of codes.Everything in the world is an object - not only the building, but also the blueprint for this building is some kind of sheet of paper.
In Java, the Class Objects are loaded as soon as you go into runtime. The VM recognizes all necessary classes, and creates one single instance of them. So, static attributes are indeed a singleton pattern on class level...
A class even has an own constructor. This constructor looks like this:
class ClassA{
// Insert Class Constructor input here
}All static attributes are implicitly constructed in this class constructor.
However, what you have written, is just a simple Form of:
class ClassA{
ClassA a;
public ClassA(){
a = new ClassA();
}This is indeed a neverending loop, so this doesn't make sense. But it isn't unusual to hold a reference to another object of the same type. -
Singleton instance vs static class
Hi,
I often got confused to identify when is better to use a singleton instance and when is better use a static class insted.
Could someone please advise what criteria should be observed to decide which way is better?
Thanks in advance,A class with all static methods generally connotes a helper class that supplies behavior or enforces business rules of other objects. A class with only state and no behavior is typically encountered in distributed systems, also known as a transfer object. Most true objects have both state and behavior. A singleton is simply a normal object that ensures only a single instance of itself will ever be created and returned for use to a caller.
- Saish -
Serialization of singleton instance
Can a singleton instance be serialized?
If yes, if a serialized singleton instance is retreived after de-serialization, does it remain a singleton?ejp wrote:
If yes, if a serialized singleton instance is retreived after de-serialization, does it remain a singleton?No.This depends on how the Singleton is implemented.
The so called Enum Singleton is guaranteed not to produce multiple instantiations even when serialized.
See Item 3 of Effective Java, 2'nd ed., by Joshua Bloch.
According to this reference the Enum Singleton: "provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization and reflection attacks" and "a single-element enum type is the best way to implement a singleton". -
Singleton instance scope - Single Instance guaranteed per JVM or per .war
Hello Everybody,
I have a Singleton Instance and I am just confused about its scope.
In case of an Web Application is the singleton instance's scope per JVM or per .war (web app) per JVM?
My understanding says, its per JVM. Can anybody please help me more on this with the thoughts that drove it?
I appologize if this question has been answered prior. I just couldn't find it.
-Harshkdgregory wrote:
if you have multiple wars that share the jar file with the common singleton, there's no way for you to prohibit another war from loading it into their context.Minor nit: jarfiles in an EAR are shared between the WARs in that EAR. Jarfiles that are in the app-server lib directory are shared between all applications (EAR or JAR) running on that app-server.
So you could share your singleton class by storing the jarfile at the appropriate level in the app-server's classloader hierarchy.I missed that one. Thanks, KDG. I was thinking about Tomcat, not a full Java EE app server that accepted EAR files.
% -
Singleton Instance variables concurrency
Below I have code from a class that is used for caching data from a database. The class is implemented as a singleton.
My question deals with the method getCacheObj(). Does getCacheObj() return a copy of the reference to cacheObj or does it return the actual cacheObj variable itself?
Specifically I am concerned about a concurrency issue when the methods refreshCache() and getCacheObj() are called simultaneously. What would happen in the following situation:
Thread 1 calls findActiveByWebsiteArea() which calls getCacheObj(). getCacheObj() returns the cacheObj for processing down the line in a jsp or other java object. Prior to thread 1 finishing the processing with cacheObj, thread 2 calls refreshCache() which resets cacheObj. Is it possible for thread 2 to clash with thread 1?
public class NewsPeer extends AncestorCachePeer {
// object that will house the cached data
protected static NewsPeer cacheObj = null;
// attributes for the instantiated cache object
private Hashtable newsByWebsiteArea = null;
private NewsPeer() {
// private constructor to enforce a singleton
public static void refreshCache() throws Exception {
// reset the cache object so a fresh retrieve will be performed
// the next time the cache is accessed
synchronized (cacheObj) {
cacheObj = null;
private static NewsPeer getCacheObj() throws Exception {
synchronized (cacheObj) {
if (cacheObj == null) {
cacheObj = new NewsPeer();
cacheObj.retrieveCache();
return cacheObj;
public static List findActiveByWebsiteArea(String websiteareaId) throws Exception{
// get item from cache obj
return (List) getCacheObj().newsByWebsiteArea.get(websiteareaId);
private void retrieveCache() throws Exception {
// code to populate newsByWebsiteArea on cacheObj
}1) Do I really need to have a singleton to house the
cached data, or is it kosher to have the static
variable newsByWebsiteArea on the class
itself?That IS a singleton. You have exactly one instance of something. That's what a singleton is. It's true that you don't have any instances of NewsPeer, but you do have exactly one instance of the things you're interested in.
2) Will my code require synchronized methods for
findActiveByWebsiteArea() and
findActiveByLocation()? I don't want to have
issues inside these methods while the
refreshCache() method is running.Yes.
3) If I have other non-synchronized static
methods in this class, will the thread calling the
non-synchronized methods have to wait until the
synchronized methods are finished executing?No. Only synchronized methods or blocks respect the locks held by other synchronized methods or blocks.
If so, would it be a better idea to go back to synchronizing
blocks of code instead of methods to ensure maximum
efficiency?Your earlier examples synchronized on the entire method's code. I don't understand why you would think that would work differently than just synchronizing the method itself. The lock is held for exactly the same code.
Now if the critical block was only part of the method, you might want to synchronize on that. But in your case it isn't.
However: you actually have two independent objects there. So you could do something like this: public class NewsPeer extends AncestorCachePeer {
// attributes for the instantiated cache object
private static Hashtable newsByWebsiteArea = new Hashtable();
private static Hashtable newsByLocation = new Hashtable();
static {
try {
refreshCache();
} catch (Exception e) {
e.printStackTrace();
public static List findActiveByWebsiteArea(String websiteareaId) throws Exception{
synchronized(newsByWebsiteArea) {
// get item from cache obj
return (List) newsByWebsiteArea.get(websiteareaId);
public static List findActiveByLocation(String locationId) throws Exception{
synchronized(newsByLocation) {
// get item from cache obj
return (List) newsByLocation.get(locationId);
public static void refreshCache() throws Exception {
// retrieve items that will be cached
synchronized(newsByWebsiteArea) {
newsByWebsiteArea.clear();
// additional code to populate newsByWebsiteArea
synchronized(newsByLocation) {
newsByLocation.clear();
// additional code to populate newsByLocation
}That way the two "find" methods don't block each other. (Note that I changed your code slightly so you don't create new objects in the refresh() method. That's because the revised code synchronizes on the objects in question, so creating new objects would lead to synchronization failures.
Or as stefan.schulz suggests, you could use Java 5 synchronization tools to improve this. I don't know much about them but I'm pretty sure there's something that lets readers share the data without blocking and only blocks when writers are active. That's probably worth looking into. -
Referencing a instance inside a Class
Hi --
I am working on converting a movie clip to a Class so that I
can more easily
reuse it in later projects.
I have pretty succesfully converted my AS code from my
include file to a
Class file. However, I have two objects on the stage, topBG
and botBG and
whenever I reference these items inside my code, such as
botBG._y I get an
error at compile time saying "There is no property with the
name 'botBG'"
How can I set it so these assets can be referred to inside my
code?
The code worked fine when it was just a movie.. Also, this is
ActionScript
2.0.
Thanks
RichHi --
Thanks for responding. What I had created was this:
I have a movie clip, "MainClip" with two movie clips ("ClipA"
and "ClipB")
inside that clip.
I put MainClip on the stage (_root) and had Actionscript code
in the main
time line. I referenced ClipA & ClipB this way:
MainClip.ClipA
MainClip.ClipB
Now, I want to turn MainClip into a class, "classMainClip".
However, having
moved the Actionscript into the class AS file and changed the
above
reference to just
ClipA
ClipB
I get an error at compile time.
How do I refer to the movie clips, "ClipA" and "ClipB" inside
the
actionscript that is the over lying class of which I want
these clips to be
a part?
Hopefully I've explained this right.
Thanks,
Rich
"kglad" <[email protected]> wrote in message
news:gibuh8$qbh$[email protected]..
> you want class instances to be able to reference each
other? -
How can I run two instances of Firefox: one in Safe Mode and another in Normal Mode?
I think my question says it all.
You can't simultaneously run a normal instance and a Safe Mode instance using the same profile. So step one is to create a new profile.
* [[Use the Profile Manager to create and remove Firefox profiles]]
Right-click the desktop and choose New, then Shortcut. As the location of the item, use the following, substituting the placeholder profile name with the actual profile name you chose earlier.
"C:\Program Files (x86)\Mozilla Firefox\firefox.exe" -no-remote -p NameOfTheProfile
* https://developer.mozilla.org/docs/Mozilla/Command_Line_Options -
"java.lang.ClassNotFoundException" when creating a CFC instance inside a webservice
This question is also up on stack overflow: http://stackoverflow.com/questions/10089962/coldfusion-web-service-failing-to-see-componen t
I've got a CFC that I'm going to access with ?wsdl as a SOAP webservice.
If I call the CFC directly in a browser, my results render fine:
http://server/webservice/calc.cfc?method=doStuff&foo=bar
If I try to access it as a web service:
ws = CreateObject("webservice", 'http://server/webservice/calc.cfc?wsdl');
result = ws.doStuff('bar');
I get an error:
Cannot perform web service invocation doStuff.
The fault returned when invoking the web service operation is:
AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: coldfusion.xml.rpc.CFCInvocationException:
[coldfusion.xml.rpc.CFCInvocationException : [java.lang.ClassNotFoundException :
com.calculations.calc][java.lang.NullPointerException : null]]
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}stackTrace:coldfusion.xml.rpc.CFCInvocationException: [coldfusion.xml.rpc.CFCInvocationException : [java.lang.ClassNotFoundException :
com.calculations.calc][java.lang.NullPointerException : null]]
at coldfusion.xml.rpc.CFComponentSkeleton.__createCFCInvocationException(CFComponentSkeleton.java:733)
at coldfusion.xml.rpc.CFComponentSkeleton.__convertOut(CFComponentSkeleton.java:359)
at webservice.calc.doStuff(/var/www/vhosts/server/httpdocs/webservice/calc.cfc)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.r... ''
The problem is because the doStuff function is declaring an instance of a CFC inside it:
remote struct function doStuff(foo) {
var objReturn = {};
objReturn.msg = 'A message';
// do a calculation
var objCalc = new com.calculations.calc(foo);
objReturn.calc = objCalc;
return objReturn;
So my CFC that I'm using as a webservice has got another CFC being declared inside a function. Browsing directly to my webservice CFC works fine, but trying to call it using the CreateObject/webservice route fails, as it can't create an instance of the **com.calculations.calc** component.
It doesn't error, wierdly, if I comment out the objReturn.calc = objCalc line. So it seems I can create the instance, but the error isn't thrown till I assign it to my return struct.
Also I've found, If I refresh the page a few times, sometimes the error changes to:
AxisFault
faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
faultSubcode:
faultString: coldfusion.xml.rpc.CFCInvocationException:
[coldfusion.xml.rpc.CFCInvocationException : [java.lang.ClassNotFoundException :
com.calculations.calc][coldfusion.xml.rpc.CFCInvocationException :
returnType must be defined for remote CFC functions.]]
faultActor:
faultNode:
faultDetail:
{http://xml.apache.org/axis/}stackTrace:coldfusion.xml.rpc.CFCInvocationException:
[coldfusion.xml.rpc.CFCInvocationException : [java.lang.ClassNotFoundException :
com.calculations.calc][coldfusion.xml.rpc.CFCInvocationException :
returnType must be defined for remote CFC functions.]]
at coldfusion.xml.rpc.CFComponentSkeleton.__createCFCInvocationException(CFComponentSkeleton.java:733)
at coldfusion.xml.rpc.CFComponentSkeleton.__convertOut(CFComponentSkeleton.java:359)
at webservices.TaxCalc.feed.getTaxCalc(/var/www/vhosts/server/httpdocs/webservice/calc.cfc)
at sun.reflect.Nat... ''
Message was edited by: PeteComcar - impvoed code formatting and added returntype updateDear All Technology Expert's,
I have a query related to Coldfusion SOAP services, that is most commonly asked in all the forum's but NONE of them has got answer.
If there is NO solution so I think Adobe has to come up with some patches so developer can able to do some customization.
I like to share with you all, in all other language ( PHP, JAVA, .NET etc) this option is available and you can customize the error.
Ok let me again explain the very basic error:
SOAP Request:
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Header/>
<soapenv:Body>
</soapenv:Body>
</soapenv:Envelope>
SOAP Response:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<soapenv:Fault>
<faultcode>soapenv:Server.userException</faultcode>
<faultstring>java.lang.Exception: Body not found.</faultstring>
<detail>
<ns1:stackTrace xmlns:ns1="http://xml.apache.org/axis/">java.lang.Exception: Body not found.
at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:121)...</ns1:s tackTrace>
<ns2:hostname xmlns:ns2="http://xml.apache.org/axis/">Coldfusion Error</ns2:hostname>
</detail>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
HOW we can customize the error, in all other languages you can simple customize the error like
Other languages SOAP response:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<soapenv:Fault>
<faultcode>BODY_NOT_FOUND</faultcode>
<faultstring>Body is missing in your request</faultstring>
</soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>
But the same is NOT possible in Coldfusion, right?
AS you know it is vulnerability to display exception messages in the response.
We are developing this web service to access from other language website (PHP, .NET).
We are also planning to upgrade server the Coldfusion 11, but do you think there is any solution with latest Coldfusion version.
Please response only if you know about these issue's or solution.
Thanks
Niyaz -
Using placed/named instances inside another movieclip
I'm trying to be good and make all my movieclips linked to a
class file, but I'd still like the convenience of placing and
naming other instances instead of having to declare a variable,
instantiating it and addChild-ing it in the class file. Is this
possible?
Here's the situation: I've created a library.fla with
components, for example LCARSButton and LCARSElbow. But now I want
to build movie clips (inside of library.fla) that use these
components, for example LCARSPrefs.
I can create a frame script inside of LCARSPrefs that
positions the instances of LCARSButton and LCARSElbows that I
placed and named on the stage of LCARSPrefs. But if I try linking
LCARSPrefs to a class file, say LCARSPrefs.as, I'll get an 1120
error telling me that I haven't declared the variables that
correspond to the instances of LCARSButton and LCARSElbow that I
placed on the stage.
Is it impossible to mix these two approaches? If you link to
a class, are you forced to use code to declare and add instances of
components?
I would prefer to have a mix of these approaches because I'm
trying to create a runtime shared library of components and the
movies that incorporate these components. For instance, I want
logs.fla to import LCARSPrefs from the library and I want to see a
visual representation of that imported instance. But if I can't
place instances of the components into the LCARSPrefs movieclip
back in library.fla, I will see nothing when I import it into
logs.fla.
I could make LCARSPrefs yet another component, thus giving it
a livePreview, but that seems overkill to me.
I'd appreciate any help.
Thanks,
JenniferOK, I've attached one solution that just seems horribly
convoluted to me. I have to create a new variable that's just a
reference to the placed instance: _square_mc =
SquareComponent(getChildByName("square_mc"));
Or is there a simpler method?
Again, thanks, Jennifer -
Oracle singleton instance issue with OCIStmtFetch()
Hi,
i am folowing a singletom pattern in my VC++ application were only one Oracle instance is created and it is being used through out the application. The OCIStmtFetch() is used twice in the application and when the OCIStmtFetch() is invoked for the second time it returns a OCI_NO_DATA condition. But when i created a new instance of Database use it to invoked the OCIStmtFetch() for the second time it gives a proper result. please can some one help me on why the singleton DBinstance is causing issue with the OCIStmtFetch() for the second time.This forum is about general programming in C, C++, and Fortran, and specifically about using the Oracle Solaris Studio suite of programming tools. Since your question is about using VC++ with Oracle database, you are not likely to get a helpful answer here. (Oracle Solaris Studio is not available on Windows.)
I suggest you try an Oracle database programming forum. Start here:
Database -
Converting Single Instance database into Oracle Fail-Safe on Linux
Hi All,
We have single instance Oracle10g database running on Linux RHEL4. We are looking to convert this database into Oracle Fail-Safe (Active-Passive). Does any one have document for Oracle fail-safe setup?
Regards,
TusharTushar,
you can't use software for windows on Linux.
However, there's number of ways to implement high-availability solution on Linux Oracle.
You can go with Active-Active (RAC) - which means that you'll have two servers attached to the same database at the same time. You can use either, and if one goes down(due to power failure for instance), the second will still be available.
You can go with Active-Passive (Data Guard) - which means that you'll have one of the nodes being active and the second passive, but synchronized with the first one, so in case of failure of the first node you can activate the second one.
You can also go with linux clustering - which is most similar to MCS + fail-safe - you'll have two nodes clustered with linux clustering software (RH cluseter suite for instance) and connected to shared storage. One node is active, and in case of crash database instance will be automatically started on the second node. This is beneficial because you can use your resources more efficiently. In case if you have two databases you can run each of them on dedicated server and then, in case of node failure move to another one. However, the setup of such configuration is quite cumbersome. -
Ensuring one singleton instance for multiple JVMs
i am creating a singleton object. But singleton is per JVM (or rather per classloader) right? But i want to ensure only one instance of my singleton even if there are multiple jvms....how can i achieve that?
javanewbie80 wrote:
i am creating a singleton object. But singleton is per JVM (or rather per classloader) right? But i want to ensure only one instance of my singleton even if there are multiple jvms....how can i achieve that?You can't.
Given computers A and B. Neither have any connectivity by any means to the other.
Install the application on both and run it. There is no way for either application to know about the other thus only one of the following is possible.
1. Both applications run and create an instance. Then there are two instances and thus it fails.
2 The application refuses to run. Then there are none and thus it fails
Other solutions are possible given that some reasonable requirements based on actual business driven needs are presented. -
Center label instance inside VGroup in Flex
Hi all I am trying to center my labels below my image inside my VGroup.
The labels are align to left now and it seems like HorizontalAlign is not working on spark component.
Anyone knows how to fix it? Thanks a lot.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:VGroup width="800">
<mx:Image source="images/big/city1.jpg"/>
<s:Label text="test1" horizontalCenter="0" /> //doesn't work....:(
<s:Label text="test2" />
</s:VGroup>
</s:Application>horizontalAlign="center"
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="955" minHeight="600">
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:VGroup horizontalAlign="center" width="100%">
<s:Label text="test1"/>
<s:Label text="test2" />
</s:VGroup>
</s:Application>
If this post answers your question or helps, please mark it as such.
Greg Lafrance - Flex 2 and 3 ACE certified
www.ChikaraDev.com
Flex Training and Support Services -
Is it possible to write a doPost() method inside a doGet() method??
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class check extends HttpServlet
protected void doGet ( HttpServletRequest rq, HttpServletResponse rp ) throws ServletException, IOException
protected void doPost ( HttpServletRequest rq, HttpServletResponse rp ) throws ServletException, IOException
}I tried the above code and failed. So, if someone could answer me, I'd be really grateful!
Thanx in advance.I tried the above code and failed. So, if someone could answer me, I'd be really grateful!
Thanx in advance.This code is simply illegal Java code. It has nothing to do with "doPost()" or "doGet()". Go back to school/books and carefully learn Java.
If you want to write logic for GET requests, implement doGet(). If you want to write logic for POST requests, implement doPost(). Otherwise just leave it away. If you want GET and POST requests behave both the same (I have never had such an odd requirement, but that's another story .. you're the developer here), then just let them call both the same method. Add private void doSomething(req, res) and let the doGet() and doPost() call it. Simple, isn't it?
Maybe you are looking for
-
Everytime I get near this Mac I do something to it. Today I have managed to make my screen small and have no idea how to make it bigger.
-
What is the max ddr voltage for the 875p neo-fisr (the one with the orange pci slot)? Thanks!
-
Calling a Browser window from a method
Hi All, I have added a new button in the toolbar of a PCUI application. My requirement is to open a new browser window on click of this button. I have created a class ZCL_BSP_ACC_ACCMOD which is inherited from CL_BSP_ACC_ACCMOD. In this method IF_CRM
-
Hi, We are trying to build an extension on JDev 11.1.1.6. We need to get the list of all files in current project like jspx or jsff files. The ApplicationOverview sample application has given a way to get list of all files but we are not able to run
-
Import Access and Excel datafile into Oracle
Dear SQL Expert: Could you hint me how to import Access and Excel datafiles into a newly install oracle database. An outline doc on procedure would be helpful. Thanks, user607670.