I'm running a server which on occasion has to search what a client queries. I'd like to write the client query to disk for records, but I don't want to slow down the search anymore than I have to. (The search is already the bottleneck...)
So, when the client performs a search, I'm having the client's thread send a message to a singleton thread, which will handle the disk write, while the client thread continues to handle the client's requests. That way, the file on disk doesn't run into sync issues, and it doesn't slow the clients experience down.
I have a conceptual question here: is the singleton appropriate in this case? I've been using the singleton design pattern a little too much in my recent programming, and I want to make sure that I'm using it for its intended use.
Any feedback is greatly appreciated.
The singleton pattern is definitely overused and comes with its share of difficulties (unit-testing is the canonical example), but like everything in design, you need to weigh the pros and cons for your specific scenario. The singleton pattern does have its uses. There are options that may allow you to get the singleton behaviour, while alleviating some of the inherent issues:
Interception (often referred to as aspect oriented programming, though I've seen debate that they are not exactly the same thing... can't find the article I read on this at this time) is definitely an option. You could use any combination of construction injection, the decorator pattern, an abstract factory and an inversion of control container. I'm not up on my Java IoC containers, but there are some .Net containers that allow automatic interception (I believe Spring.Net does, so likely Spring (Java) has this built in). This is very handy for any type of cross-cutting concerns, where you need to perform certain types of actions across multiple layers (security, logging etc.). Also, most IoC containers allow you to control lifetime management, so you would be able to treat your logger as a singleton, without having to actually implement the singleton pattern manually.
To sum it up. If a singleton fits for your scenario (seems plausible from your description), go for it. Just make sure you have weighed the pros and cons. You may want to try a different approach and compare the two.
Related
I am trying to have an annotation #FeatureDependent be used on methods to signal that the method requires certain things to be enabled in order for it to work. And I was wondering if it was possible to have a method called everytime a method with #FeatureDependent was called which would check if the criteria were met for the method to be called.
It sounds like you are describing Aspect Oriented Programming (AOI). This technique allows you to address "cross-cutting" concerns, tasks like logging, security, and transaction management which tend to affect many methods in the same manner. Your use case sounds like it would be a good fit for AOP.
There are two common approaches to AOP. The first mechanism is to create objects in a container (e.g. a Spring container). The container can then scan the class, detect any advice that needs to be applied, and apply the advice via dynamic proxies (Googling Spring and AOP is a good place to start with this). The downside is that your components will need to be constructed by a container so it makes sense for larger components.
The second approach is an extra compilation step (sometimes done at compilation, sometimes done as a separate compilation phase, and sometimes done by a weaving class loader) to wire in the additional methods. This is typically called "weaving" and AspectJ is a common library to look into for this.
Both approaches will allow you to apply "advice" (code run before and after a method invocation) based on annotations on an object. Explaining either in more detail would be beyond the scope of a SO answer but I hope it can get you started.
I should warn that AOP has gotten a bit of a reputation for complicating the flow of an application and tending to be difficult to understand and debug. As a result it has declined in popularity lately.
Another approach is to use something like Servlet Filters, basically a single choke point for all requests and workflows where you can apply various logging & security mechanisms. Such an approach tends to be a little easier to understand and involve a bit less "black magic".
Starting a new GWT application and wondering if I can get some advice from someones experience.
I have a need for a lot of server-side functionality through RPC services...but I am wondering where to draw the line.
I can make a service for every little call or I can make fewer services which handle more operations.
Let's say I have Customer, Vendor and Administration services. I could make 3 services or a service for each function in each category.
I noticed that much of the service implementation does not provide compile-time help and at times troublesome to get going, but it provides good modularity. When I have a larger service, I don't have the modularity as I described, but I don't have to the service creation issues and reduce the entries in my web.xml file.
Is there a resource issue with using a lot of services? What is the best practice to determine what level of granularity to use?
in my opinion, you should make a rpc service for "logical" things.
in your example:
one for customer, another for vendors and a third one for admin
in that way, you keep several services grouped by meaning, and you will have a few lines to maintain in the web.xml file ( and this is a good news :-)
More seriously, rpc services are usually wrappers to call database stuff, so, you even could make a single 'MagicBlackBoxRpc' with a single web.xml entry and thousands of operations !
but making a separate rpc for admin operations, like you suggest, seems a good thing.
Read general advice on "how big should a class be?", which is available in any decent software engineering book.
In my opinion:
One class = One Subject (ie. group of functions or behaviours that are related)
A class should not deal with more than one subject. For example:
Class PersonDao -> Subject: interface between the DB and Java code.
It WILL NOT:
- cache Person instances
- update fields automatically (for example, update the field 'lastModified')
- find the database
Why?
Because for all these other things, there will be other classes doing it! Respectively:
- a cache around the PersonDao is concerned with the efficient storage of information to avoid hitting the DB more often than necessary
- the Service class which uses the DAO is responsible for modifying anything that needs to be modified automagically.
- To find the database is responsibility of the DataSource (usually part of a framework like Spring) and your Dao should NOT be worried about that. It's not part of its subject.
TDD is the answer
The need for this kind of separation becomes really clear when you do TDD (Test-Driven Development). Try to do TDD on bad code where a single class does all sorts of things! You can't even get started with one unit test! So this is my final hint: use TDD and that will tell you how big a class should be.
I think the thing to optimize for is that you can accomplish a result in one round trip to the server. I have an ad-hoc collection of methods on my service object, one for each situation the client finds itself in when it has to get something done. You do not want the client to RPC to the server several times in a row while the user is sitting there waiting.
REST makes things orthogonal, but orthogonality has a cost: there is a reason that the frequently used verbs in languages are irregular. In terms of maintaing clean orthogonal structure to your app, make sure your schema is well-designed. That is where each class should have semantics orthogonal to that of the other classes. When the semantics of each RPC call can be stated cleanly in the schema there will be no confusion as to what they mean, even if they aren't REST-fully ideal.
I have a Java system that consumes an API. A few days ago, we started facing the following problem: the remote API was receiving too many requests from my system. Back in the system's early days, it was not a major concern, but little by little the system's performance was getting worse and worse, since my data was growing and I made multiple requests for each entity. I noticed many of the network requests I made were not really necessary, since the data was not updated very frequently. So, I implemented a class that, when my system starts, makes an over-eager loading of all the remote API data. When I create/update an entity, I load it before any request is made. I treat deletion accordingly. And the remote API also notifies me when any change is made so I can stay updated even when this change is made outside my system.
What I really want to know is: is there any name for this practice? Any known design pattern
? I must say I've done a little research and I think it is a proxy pattern but, again, I'm not very sure (in fact, most of the design patterns look very similar), and I'm not really that much into design patterns.
I would call it a Cache System to what you implemented. Not sure if there is a dessign pattern for this though.
Also, the fact that the remote API notifies you when any change is made, might have been done using the observer pattern.
It's not quite a proxy pattern as the proxy pattern falls more under the heading of 'lazy loading'. From the description of the Proxy Pattern specified in
Design Patterns (Group of Four Book):
One reason for controlling access to an object is to defer the full
cost of its creation and initialization until we actually need to use
it
I'm not sure what you'd call it other than over-eager loading
I am trying to make a Java application thread-safe. Unfortunately, it was originally designed for a single-user mode and all the key classes are instantiated as singletons. To make matters worse, there is a whole bunch of interfaces working as constants containers and numerous static fields.
What would be considered as a good practice in this case?
There is a single entry point, so I could synchronize that and just use pooling (sort of), but if the calls take more than a minute on average, all other threads in the queue would have to wait for a long time...
Since the test code coverage is not quite optimal and I can't be sure if I overlooked something, some hints about bad implementation patterns (similar to those stated above) in this area would be useful.
I know the best thing would be to rewrite the whole structure, but this isn't an option.
It doesn't sound like there is a quick fix for this. You should probably start by refactoring the existing code to use good design patterns, with an eye for multi-threading it in the future. Implement the multi-threading as a later step, after you've cleaned it up.
#coldphusion, you'll have to read/analyze code. Using an automated tool, if such a tool exists, would be like shooting yourself in the foot.
Plus, not everything has to be thread-safe. If an object will never be accessed from multiple threads, no need to make it thread-safe. If an object is immutable, then it's already thread-safe.
Be ready to tell your boss "It won't take a few hours or a day, even you know it, so stop asking."
I recommend reading Java Concurrency In Practice.
As Jonathan mentions it's doesn't sound like there's a quick fix.
You could consider using ThreadLocal in order to provided a dedicated per-thread singleton. Obviously this may or may not be possible depending on the state stored within the singletons, whether this has to be shared / maintained, etc.
I will add to #nevermind's advice, since he/she made some very practical points.
Be practical about what you need to change to accomplish your task since there is no magic way. Your existing code, well designed or not, may only need small changes depending on how it is used. Of course this also means a complete redesign may also be in order.
There is no way for anyone here to know (unless they wrote the original code ;-)
For example, if you only need to make access to a single object (singleton or not) threadsafe, this is fairly easily accomplished, possibly without any coding impacts on the caller of such an object.
On the other hand, if you need to modify multiple objects at once to keep the integrity of your data/state, then your efforts will be considerably harder.
Singletons are not a bad thing and do not go against thread-safety, as long as they don't store any state. Just look at any J2EE app; lots of singletons, without any state (only references to other stateless singletons). All state is stored in sessions; you could maybe mimic that, but as others have said, there is no way to automagically transform your app; you will have to make some good analysis to determine how you will refactor it to separate all stateless beans from the stateful ones, maybe encapsulate state in some value objects, etc.
If anyone should be also interested on the topic - I found a pretty detailed tutorial on "what (not) to do" - with common mistakes and best practices.
Unfortunately, it's only available in German atm :|
What are the design patterns that every developer must know?
I'm interested in the context of Java web developers working with Spring & Hibernate. I have often heard that good knowledge in design patterns is essential for working with those frameworks. Can anyone list the specifics?
For example, I know that understanding abstract factory & factory pattern, singleton pattern etc is absolutely essential. I'm looking for a comprehensive list.
Inversion of Control
If you are ever going to design decoupled systems, you will need to know how to properly link dependencies between classes.
Command Pattern and Variants
In Java in particular, it is essential to learn how to pass a piece of functionality to another method as an object because of the lack of closures and function pointers in the language.
Factory Pattern
Factories are ubiquitous in Java frameworks and it is essential to learn why and when to use the factory pattern.
Singleton (pattern and anti-pattern)
Learning how to use the singleton pattern responsibly is very helpful for understanding the pitfalls in other people's code you may be reading.
Overall, learning the why with regards to patterns is much more important the the how. Knowing when not to apply a pattern is just as important as knowing when to.
Everybody should know about Singleton, but also when not to use it! It's currently the source of much pain for me on a project at work.
Singletons make the code hard to understand and follow, and make writing unit tests much more difficult. I like the blog post Singletons are Pathological Liars.
Most design patterns are pretty obvious--you already know and use them if you've been programming a few years.
The biggest advantage I've found to design patterns is sharing a common set of names. If someone says "Callback" that can mean quite a few things, but if someone says "Listener Pattern" that means a more specific set of calls and implies a higher level relationship between objects.
So in essence, read through a good design patterns book, get an idea of the name of each pattern, spend some time understanding any you don't know, and you're good to go.
I wouldn't completely ignore any of them--they are all good to have seen. You should be able to recognize a situation that might benefit from a specific pattern and know where to look to find out more about it.
Model–view–controller just has to be on the list, Spring has an MVC framework:
http://en.wikipedia.org/wiki/Model–view–controller
I recommend you to read Head First Design Patterns book. This is a well written book about all commons and useful patterns.
I would recommend you get and read the Design Patterns book, since it gives you the vocabulary.
But don't forget the fundamentals :)
Interviewing Java Developers With Tears in My Eyes
http://java.sys-con.com/node/1040135
Hibernate? Then the Unit Of Work is a must http://martinfowler.com/eaaCatalog/unitOfWork.html
Composite, it's present in the JUnit framework. (Test-TestCase-TestSuite)
The Adapter, Builder, Command, Template Method and Strategy patterns are easy and often usable in practice.
The State pattern also helped me to clean up mess in inherited source codes.
This would be a comment to Greg Hewgill's reference to "Singletons Are Pathological Liars", but I can't make comments yet.
That article makes a convincing case, but his ire is misdirected. As several commenters on his blog noted, his problem is really global state. His code fix could still be making use of singletons, and still gain the exact increase in clarity and testability.
Re-read the article. He's not bothered that OfflineQueue needs an initialized Database instance, nor that CreditCardProcessor needs an initialized OfflineQueue. He's bothered that those dependencies aren't visible, which causes issues with maintainability and testability.
His problem is with secret global state (does this make me sound like a conspiracy theorist?).
However, he's (imo) misinterpreting that secret global state as being the fault of singletons.
That doesn't mean I'm in favor of singletons where they're not necessary - certainly, they have drawbacks (including the obvious thread contention bottleneck possibility). But I prefer to be clear about what practices I'm eschewing.
Incidentally, I'd go further in my refactoring - based on the class names, I'd assert in a code review that CreditCardProcessor should, well, process the charges, so instead of his:
card.charge(cardProcessor, 100);
I'd have this, instead:
cardProcessor.chargeCard (card, 100);
(and yes, I replaced his variable names c and ccp with names I considered more readable)
Apart from Abstract factory , Factory Method and Singleton patterns, which you have quoted already, I think below patterns are useful.
Bridge Pattern : Abstraction and implementation can change independently
Decorator Pattern : Change the behaviour of object at run time
Mediator Pattern : Enable central communication medium between different objects
Chain of Responsibility : If you are adding filters to web service request, this is very useful.
Strategy Pattern : If you want to change the algorithm from a family of algorithms at run time by checking a parameter
Facade Pattern : If you have many services in your system and don't want to expose all the services to client, have one Facade class, which will interact with other services.
sourcemaking provides excellent details on each design-pattern : Intent, Strucutre, Checklist and Rules of thumb.
One more SE question would be definitely help you :
Design Patterns web based applications
Singleton - Singletons apparently can and should be used for everything