How One Servlet Will Access Other Servlet's Datamember? - servlets

I have two servlets. 1 serves as a primary server for my applet clients and other serves as secondary.
I just want for my servlet2(secondary) to ask servlet1 about number of sessions it have, suppose servlet1 is storing that information in an int, then how can we access that int from servlet2. provided that both servlets are different web projects.

This is a bad design you are trying to implement. What you really need is an Application Scope Variable
Quoting from http://www.daniweb.com/web-development/jsp/threads/78622/difference-between-session-and-application-scope-at-jsp
'Application scope is the broadest scope and should only be used when necessary. You can create objects bound at application level in JSPs that are not session-aware, so application scope is useful for storing information when using these types of JSPs. You can also use application-bound objects to share data among different sessions of the same application.'
Take a look at this example that makes use of a counter as Application Scope Variable http://java.sun.com/developer/onlineTraining/JSPIntro/exercises/Counter/index.html

Related

Should instance variables not be used since they cause mulithreading problems?

I understand that instance variables are not thread safe because they are stored on the heap. I am refactoring code in an ASP.NET single threaded application and I am trying to use instance variables more.
My question is: do developers avoid using instance variables because of possible multi threading problems? (even if the app is not multi threaded now it may be in the future). I remember reading that instance variables should be used to improve design using composition and aggregation rather than association (as with local variables).
Is there any criteria that helps a developer to decide when to use instance variables and when to use local variables. I have Googled this and I have looked on MSDN but I have not managed to find an answer to my specific question.
Have you done anything to make the ASP.NET application single threaded? Otherwise it's multi treaded by default.
Instance variables is only a problem with multi threaded applications if you share the object between threads. Normal for an ASP.NET application is that each thread creates its own instances of the objects, so the multi threading is not a problem.
If you need to share data between threads, encapsulating the data in an object is still the best approach. By using private instance variables and access them through methods or properties, you can make sure that all access from outside the object is synchronised, as the code in the object has full control over where the data is exposed.
You are in fact referring to static variables. Static variables are not thread-safe (in general, unless you write code to synchronize appropriate access to the variable). Instance variables, in contrast, are thread-safe in asp.net since each request thread will operate on its own copy.
static variables are meant to store data that needs to be shared among all requests. If you don't have such scenario, you shouldn't need to use static variables. And if you do, there are classes that already provide for this, such as the Cache class.
Assuming are talking about web pages and instance variable of web page then you do not have to worry about the multi-threading and thread safety. The asp.net/web server will take care for that. This msdn article discuss the thread safety provide by asp.net.

is it possible to have a global variable between two WCF services?

Is it possible to have a global variable accessible between two WCF services?
I have written a WCF service to upload an excel file using AJAX uploader. I am trying to read a global variable which I would set in the upload service in another service.
Is this possible or is this approach right?
Trying to introduce global variables into an otherwise stateless infrastructure usually isn't recommended.
Another option may be to use WCF Sessions to track state across multiple consecutive service calls by the same client - on the server, a class instance variable declared would be available to all services methods in the class which are involved in the same session (and would be scoped to just this session).
Note that a global (e.g. static) variable would be shared across all clients, which may not give the the intended behaviour if you have more than one client.
Also, remember to make any thread safety considerations.

Why use facade pattern in EJB?

I've read through this article trying to understand why you want a session bean in between the client and entity bean. Is it because by letting the client access entity bean directly you would let the client know exactly all about the database?
So by having middleman (the session bean) you would only let the client know part of the database by implementing the business logic in some certain way. So only part of the database which is relevant to the client is only visible. Possibly also increase the security.
Is the above statement true?
Avoiding tight coupling between the client & the business objects, increasing manageability.
Reducing fine-grained method invocations, leads to minimize method invocation calls over the network, providing coarse-grained access to clients.
Can have centralized security & transaction constraints.
Greater flexibility & ability to cope with changes.
Exposing only required & providing simpler interface to the clients, hiding the underlying complexity and inner details, interdependencies between business components.
The article you cite is COMPLETELY out of date. Check the date, it's from 2002.
There is no such thing anymore as an entity bean in EJB (they are currently retained for backwards compatibility, but are on the verge of being purged completely). Entity beans where awkward things; a model object (e.g. Person) that lives completely in the container and where access to every property of it (e.g. getName, getAge) required a remote container call.
In this time and age, we have JPA entities that are POJOs and contain only data. Don't confuse a JPA entity with this ancient EJB entity bean. They sound similar but are completely different things. JPA entities can be safely send to a (remote) client. If you are really concerned that the names used in your entity reveal your DB structure, you could use XML mapping files instead of annotations and use completely different names.
That said, session beans can still perfectly be used to implement the Facade pattern if that's needed. This pattern is indeed used to give clients a simplified and often restricted view of your system. It's just that the idea of using session beans as a Facade for entity beans is completely outdated.
It is to simplify the work of the client. The Facade presents a simple interface and hides the complexity of the model from the client. It also makes it possible for the model to change without affecting the client, as long as the facade does not change its interface.
It decouples application logic with the business logic.
So the actual data structures and implementation can change without breaking existing code utilizing the APIs.
Of course it hides the data structure from "unknown" applications if you expose your beans to external networks

ASP.NET A static object to hold connection with a DB. Is it a good idea?

I'm wondering if it is a good approach in the ASP.NET project if I set a field which "holds" a connection to a DB as a static field (Entity Framework)
public class DBConnector
{
public static AdServiceDB db;
....
}
That means it'll be only one object for entire application to communicate with a DB. I'm also wondering about if that object will be refreshing data changes from DB tables, or maybe it shouldn't be static and I shoud create a connection dyniamically. What do You think ?
With connection pooling in .NET, generally creating a new connection for each request is acceptable. I'd evaluate the performance of creating a new one each time, and if it isn't a bottleneck, then avoid using the static approach. I have tried it before, and while I haven't run into any issues, it doesn't seem to help much.
A singleton connection to a database that is used across multiple web page requests from multiple users presents a large risk of cross-contamination of personal information across users. It doesn't matter what the performance impact is, this is a huge security risk.
If you don't have users or personal information, perhaps this doesn't apply to your project right now, but always keep it in mind. Databases and the information they contain tend to evolve in the direction of more specifics and more details over time.
This is why you should not use a singleton design pattern with your database connection
Hope it helps
Is using a singleton for the connection a good idea in ASP.NET website
Bad idea. Besides the potential mistakes you could make by not closing connections properly and so forth, accessing a static object makes it very difficult to unit test your code. I'd suggest using a class that implements an interface, and then use dependency injection to get an instance of that class wherever you need it. If you determine that you want it to be a singleton, that can be determined in your DI bindings, not as a foundational point of your architecture.
I would say no.
A database connection should be created when needed to run a query and cleaned up after that query is done and the results are fetched.
If you use a single static instance to control all access to the DB, you may lose out on the automatic Connection Pooling that .NET provides (which could impact performance).
I think the recommendation is to "refresh often."
Since none of the answers have been marked as an answer and I don't believe any have really addressed question or issue thereof...
In ASP.NET, you have Global or HttpApplication. The way this works is that IIS will cache instances of your "application" (that is an instance of your Global class). Normally (default settings in IIS) you could have up to 10 instances of Global and IIS will pick any one of these instances in order to satisfy a request.
Further, keep in mind that, there could be multiple requests at any given moment in time. Which means multiple instances of your Global class will be used. These instances could be ones that were previously instantiated and cached or new instances (depending on the load your IIS server is seeing).
IIS also has a notion of App Pools and worker processes. A Worker process will host your application and all the instances of your Global classes (as discussed earlier). So this translates to an App Domain (in .NET terms).
Just to re-cap before moving on…
Multiple instances of your Global class will exist in the Worker process for your application (in IIS). Each one waiting to be called upon by IIS to satisfy a request. IIS will pick any one of these instances. They are effectively threads that have been cached by IIS and each thread has an instance of your Global class. When a request comes in, one of these threads is called upon to handle the request-response cycle. If multiple requests arrive simultaneously, then multiple threads (each contains an instance of your Global class) will be called upon to satisfy each of those requests.
Moving on…
Since there will be only one instance of a static class per App Domain you'll effectively have one instances of your class shared across all (up to 10) instances of Global. This is a bad idea because when multiple simultaneous requests hit your server they'll either be blocked (if your class’s methods use locks) or threads will be stepping on each other’s toes. In other words, this approach is not inherently thread-safe and if you make it thread safe using thread synchronization primitives then you’re unnecessarily blocking threads, negatively impacting performance and scalability of your web application, with no gain whatsoever.
The real solution (and I use this in all my ASP.NET apps) is to have an instance of your BLL or DAL (as the case may be) per instance of Global. This will ensure the following:
1. Multiple threads are not an issue since IIS guarantees one request-response per instance of Global) at any given moment in time. So you’re code is inherently threads-safe.
2. You only have up to 10 instances of your BLL/DAL up and running at any given moment in time ensuring that you're not constantly creating and disposing instances of (typically) large objects to satisfy each request, which on busy sites is huge
3. You get really good performance well due to #2 above.
You do have to ensure that your BLL/DAL is truly stateless or that you reset any state at the start of each Request-Response cycle. You can use the BeginRequest event in Global to do that is you need to.
If you go down this route, be sure to read my blog post on this
Instantiating Business Layers – ASP.NET

Object integrity and caching in a stateful client

I'm wondering what strategies exist to handle object integrity in a stateful client like a Flex or Silverlight app.
What I mean is the following: consider an application where you have a Group and a Member entity. Groups contain multiple members and members can belong to multiple groups. A view lists the different groups, which are lazy loaded (no members initially). When requesting the details of the group, all members are loaded and cached so the next time we don"t need to invoke a service to fetch the details and members of the group.
Now, when we request the details of another group that has the same member of a group that was already loaded, would we care about the fact that the member is already in memory?
If we don't, I can see a potential data conflict when we edit the member (referenced in the first group) and changes are not applied to the other member instance. So to solve this, we could check the result of the service call (that gets the group details) for members that are already loaded and then replace the loaded ones with the cached ones.
Any tips, ideas or experiences to share?
What you are describing is something that is usually solved by a "first-level cache" (in Hibernate, the "Session"; in JPA, the "EntityManager") which ensures that only one instance of a particular entity exists in a particular context. As you suggest, this could be applied to objects as they are fetched from the server to ensure that all references to a particular entity are in fact references to the same object instance. You would also need a mechanism to ensure that entities created inside the AVM exist in that same context so they have similar logic applied to them.
The Granite Data Services project has a project called "Tide" which aims to solve this problem:
http://www.graniteds.org/confluence/display/DOC/6.+Tide+Data+Framework
As far as DDD goes, it's important not to design the backend as a simple data access API, such as simply exposing a set of DAOs or Repositories. The client application cannot be trusted and in fact is very easy to manipulate with a debugging proxy such as Charles. I always design a services API that is tailored to the UI (so that data for a screen can be fetched in a single call) and has necessary security or validation logic enforced, often using annotations and Spring AOP.
What I would do is create a client side application service which does the caching and servicing of requests for data. This would handle whether an object already exists in the cache. If you are using DDD then you'll need to decide what is going to be your aggregate root entity. Group or Member. You can't have both control each other. There needs to be one point for managing loading etc. Check out this video on DDD at the Canadian ALT.NET OpenSpaces. http://altnetpedia.com/Calgary200808.ashx

Resources