i just have two questions about two methods used in many controllers/servlets in my app:
1-what is the difference between calling a static method in a util class or a non static method (like methods dealing with dates i.e getting current time,converting between timezones), which is better ?
2-what is the difference between calling a method(contain too many logic like sending emails) in the controller directly or running this method in a different thread ?
1)
Utils classes generally don't have any state associated with them. They just have behavior. Hence there really isn't much point in creating "instances" of them.
Even though compiler won't ever complain, instantiating a Util class would be a misleading coding.
Being Stateless Utils classes are completely thread safe. Class methods, whether static or not, get copied to every threads stack frame and cause no interference to each other. Java Utils classes are excellent examples of this.
2)
If your method is time consuming one, it makes sense to make it's call asynchronous.
There are advantages and disadvantages to using static methods:
Advantages:
You don't have to instantiate an object to use them.
Static variables defined in the class stay the same between calls.
Disadvantages:
You can only access static variables and static methods without creating an instance of an object to call them on.
Not inherently thread-safe... You must synchronize either the method or a section of code if you don't want other threads changing variables on you.
In my personal experience, static methods are great for things that don't require you to maintain state between calls. Like formatting dates.
Having said that, time operations are pretty easy.
Getting the current time is as easy as:
Date currentDate = new Date();
or
Calendar currentCal = Calendar.getInstance();
Calendar can also be used to roll Calendar.HOUR_OF_DAY (and Calendar.MINUTE if necessary) if you know the difference between the time zones.
1: So the static keyword only tells you about the accessibility of the method. If the method is static it can be accessed without instantiating an object. So it doesn't make sense to ask which is better: static or non-static.
2: Calling a method that has some time-consuming logic on a separate thread allows your main thread to continue working on some other things which are important. So if you have two time-consuming tasks that you need to execute for a client, then running those two tasks on separate thread can get the job done faster.
Note that all of this is said with the assumption that the programmer knows how to do proper threading... if the threading is not done correctly, then there could be a slew of problems: deadlocks, invalid object states, decreased performance, etc.
#1 Seems to have been answered well in other responses.
#2 Depends on the circumstance. If the controller is having to wait for the other thread to finish with the sending email task before it can continue then there is no speed improvement at all -- in fact there would be speed loss due to the context switch and synchronization. If the controller can service another request or if it can do something else in parallel with the email sending thread then there would be a gain.
Typically, if a controller needs to send email, it gives the job off to a worker thread and then continues on its way in parallel and handles the next request. This is faster but it means that there is no way to report back problems to the caller if the email sending failed.
Related
I'm looking at legacy code and found the following:
private static final SimpleDateFormat sdf = new SimpleDateFormat("...");
...
void foo() {
bar(date, someMoreArgs, sdf.clone());
}
where bar() then goes ahead and uses the passed SimpleDateFormat to format the given date.
Is the above code thread-safe? If multiple threads concurrently call sdf.clone(), can one of the cloned objects end up getting corrupted?
I wouldn't write the code like that myself in the first place. I know there are better ways to do this. But I'm not looking to refactor the code unless it can be proven to be not thread-safe.
Edit:
Some more information for clarification:
The static object sdf itself is never used for formatting. The only operation it's ever used for is cloning. Thus, I'm not expecting its contents to change (unless the cloning operation writes some transient data inside the object).
The clone is never used by more than one thread.
From the JavaDoc:
Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.
So I believe that it depends on how you use that clone, but it is not assured. Cloning does not make your classes thread-safe. If the cloned object is not shared between class instances it should work with no problems, but I would not recommend this approach. However, you need a thread-safe date formatter I would suggest using Apache Commons FastDateFormat, described here.
Basically the clone() method doesn't give you thread safety. It just copies the properties of one object to another one. It doesn't lock or synchronize that object so if it is thread safe or not is up to the implementation. If during that copy some of the properties of the original object are changed then you might get into a strange state. If you use that cloned object in more than one threads - you still got problems
For your particular example I think the code is fine. The sdf object you are going to clone is probably never gonna change and you don't need a lock or something (it seems). You just create a new SimpleDateFormat object for each thread to ensure thread safety - or at least that's the idea - and you achieve that by using clone.
Anyway if you have spotted a problem in legacy code and you don't like it it is always better to spend some time and refactor it than to keep it like that even if you don't like it. It almost always pays off in the long term with having better and more maintainable code and not leaving that like that for the next developer to wander. For example if you have upgraded to java 8 you can use DateTimeFormatter which is thread safe or you can use some external library. Or at least create a new SimpleDateFormat(SOME_CONSTANT_FORMAT) everytime you need one instead of relying on clone of the object - because if you share just a string constant (the actual format) it is immutable and thread safe.
This is not an answer. But some information you may still find interesting. I did a couple of experiments.
First I had two threads formatting dates using the same SimpleDateFormat instance. After a couple of iterations they began giving incorrect results, and after a few hundred iterations one of the threads crashed. So the thread-unsafety seems very real.
Next I had one thread format dates using the original SimpleDateFormat and the other one taking clones of it and using the clones for formatting. Both threads have run for several minutes now and are still both producing correct results.
This is by no means any guarantee that this is the behaviour you will always see. The documentation is pretty clear: SimpleDateFormat is not thread safe and all access from several threads must be synchronized. So use the information at your own risk.
EDIT: Inspecting the source code seems to reveal that the clone operation copies fields in some order, but doesn’t modify the original. If the original was doing any work in another thread, this might cause the clone to be in an inconsistent state after creation, which in turn might or might not affect its correct working. If the original is only used for cloning, I see no risk with the current implementation. As you say, the implementation may be changed in later Java versions, but I would consider the risk small, and the risk of thread-unsafe behaviour being introduced even smaller. All of this is pure speculation!
I am just trying to come up the use cases where developer may need to use Singleton class . Here they are:-
When we need to maintain the synchronization among resources. For
example in case of logging, multiple threads need to write to single
log file in sequence. Here singleton helps as synchronization is
required among different threads so that they write in single file
in sequence.
When object creation itself is costly which means it time
consuming operation . For example :- hibernate factory creation at
start up. I am not saying this is the case in every situation but
yes in some cases singleton helps here when same state needs to be
shared across application and object creation is costly.
In case of business service objects , singleton helps as it
forces us not to maintain the state of object which in turn makes
code better unit testable.
Is my understanding on the right track?
I was looking for example of singleton in jdk and came across Runtime class and thought why this singleton? As per my understanding reason should be the first one. For example we need synchronization so that two threads doesn't run GC at same instant. Is my logic correct?
Every Java application has a single instance of class Runtime that
allows the application to interface with the environment in which the
application is running.
It feels intuitive that since the environment in which the Java program is executing is one, static thing which is not going to change, Runtime is made singleton.
The number of processors, the total RAM, etc are not going to change even if you spawn more and more threads. Thus, making Runtime a singleton instance optimizes the execution of the program by avoiding having to create an object that contains the same information as 1000 other threads.
This is my understanding of it.
Singletons are evil. They're really global variables in disguise. They're particularly bad for unit tests as once the singleton is loaded by a classloader, it's behaviour is fixed so you can't mock it. Your code will be fixed to call that dependency forever.
A better approach would be to use dependency injection to inject that dependency exactly to where it's needed, or to pass down the dependency through your code to where it's needed.
Have a read of: http://c2.com/cgi/wiki?SingletonsAreEvil
Also you ask yourself why you would want to use a singleton. A singleton means one instance but it really means one instance per classloader. This may or may not be what you really desire for your solution.
I have multiple client handler threads, these threads need to pass received object to a server queue and the sever queue will pass another type of object back to the sending thread. The server queue is started and keeps running when the server starts.I am not sure which thread mechanism to use for the client handler threads notified an object is sent back. I don't intend to use socket or writing to a file.
If you wanted to do actual message passing take a look at SynchronusQueue. Each thread will have reference to the queue and would wait until one thread passed the reference through the queue.
This would be thread safe and address your requirements.
Though if you are simply looking to have threads read and write a shared variable you can use normalocity's suggestion though it's thread-safety depends on how you access it (via sychronized or volatile)
As far as making objects accessible in Java, there's no difference between multi-thread and single-thread. You just follow the scope rules (public, private, protected), and that's it. Multiple threads all run within the same process, so there isn't any special thread-only scope rules to know about.
For example, define a method where you pass the object in, and make that method accessible from the other thread. The object you want to pass around simply needs to be accessible from the other thread's scope.
As far as thread-safety, you can synchronize your writes, and for the most part, that will take care of things. Thread safety can get a bit hairy the more complicated your code, but I think this will get you started.
One method for processing objects, and producing result objects is to have a shared array or LinkedList that acts as a queue of objects, containing the objects to be processed, and the resulting objects from that processing. It's hard to go into much more detail than that without more specifics on what exactly you're trying to do, but most shared access to objects between threads comes down to either inter-thread method calls, or some shared collection/queue of objects.
Unless you are absolutely certain that it will always be only a single object at a time, use some sort of Queue.
If you are certain that it will always be only a single object at a time, use some sort of Queue anyway. :-)
Use a concurrent queue from the java.util.concurrent.*.
why? Almost guaranteed to provide better general performance than any thing hand rolled.
recommendation: use a bound queue and you will get back-pressure for free.
note: the depth of queue determines your general latency characteristics: shallower queues will have lower latencies at the cost of reduced bandwidth.
Use Future semantics
why? Futures provide a proven and standard means of getting asynchronous result.
recommendation: create a simple Request class and expose a method #getFutureResponse(). The implementation of this method can use a variety of signaling strategies, such as Lock, flag (using Atomic/CAS), etc.
note: use of timeout semantics in Future will allow you to link server behavior to your server SLA e.g. #getFutureResponse(sla_timeout_ms).
A book tip for if you want to dive a bit more into communication between threads (or processes, or systems): Pattern-Oriented Software Architecture Volume 2: Patterns for Concurrent and Networked Objects
Just use simple dependency injection.
MyFirstThread extends Thread{
public void setData(Object o){...}
}
MySecondThread extends Thread{
MyFirstThread callback;
MySecondThread(MyFirstThread callback){this.callback=callback)
}
MyFirstThread t1 = new MyFirstThread();
MySecondThread t2 = new MySecondThread(t1);
t1.start();
t2.start();
You can now do callback.setData(...) in your second thread.
I find this to be the safest way. Other solutions involve using volatile or some kind of shared object which I think is an overkill.
You may also want to use BlockingQueue and pass both of those to each thread. If you plan to have more than one thread then it is probably a better solution.
With reference to the java.util.concurrent package and the Future interface I notice (unless I am mistaken) that the ability to start a lengthy tasks and be able to query on the progress only comes with the SwingWorker implementing class.
This begs the following question:
Is there a way, in a non-GUI, non-Swing application (imaging a console application) to start a lengthy task in the background and allow the other threads to inspect the progress ? It seems to me that there is no reason why this capability should be limited to swing / GUI applications. Otherwise, the only available option, the way I see it, is to go through ExecutorService::submit which returns a Future object. However, the base Future interface does not allow monitoring the progress.
Obviously, the Future object would only be good for blocking and then receiving the result.
The Runnable or Callable object that you submit would either have to know how to provide this progress (percentage complete, count of attempts, status (enum?) etc) and provide that as an API call to the object itself, or posted in some lookup resource (in memory map or database if necessary). For simplicity I tend to like the object itself, especially since you're going to most likely need a handle (id) to lookup the object or a reference to the object itself.
This does mean that you have 3 threads operating. 1 for the actual work, 1 that is blocked while waiting for the result, and 1 that is a monitoring thread. The last one could be shared depending on your requirements.
In my case I passed a HashSet, with the Objects to process, as Parameter to the Method, wich was created as instance variable in the calling Class. When the asyncronous method removes the Objects after processing one can retrieve the size of the Map remaining in the calling Method. I thing in general passing Objects by Reference solves the Problem.
I was hoping that there was a standard concurrency framework way to stay updated on the progress of a long running task without requiring the client program to worry about orchestrating and synchronizing everything correctly. It seemed to me to that one could fathom an extended version of the Future<T> interface that would support:
public short progress(); in addition to the usual isDone() and get() methods.
Obviously the implementation of the progress() would then need to poll the object directly so maybe Future<T> would need to be specified as Future<T extends CanReportProgress> where CanReportProgress is the following interface:
public interface CanReportProgress {
public short progress();
}
This begs the question of why one would bother to go through the Future object as opposed to calling the object itself to get the progress. I don't know. I'll have to give it more thought. It could be argued that it is closer to the current contract / semantics whereby the Callable object is not, itself, accessed again by the client programmer after the call to ExecutorService::submit / execute.
My question is about threads being queued. For my example I have one Spring context. I have a method named CalculateTax in a stateless class. A request comes in, a thread is created (tA) and it eventually enters the CalculateTax method. Within the same "time frame" another request comes in and another thread is created (tB). Now, here is what I want to understand. AFAIK tB cannot execute CalculateTax until tA has exited the method. Is this true?
As long as CalculateTax only uses local variables (i.e. declared in the method), you will not have any thread sync issues and multiple threads can call the method without a problem.
However if for some reason CalculateTax uses variables defined at the class level, and you are using the Singleton pattern (you tagged your question with "singleton", so I guess you are), you may have thread sync issues.
No it is not true if they are parallel thread, each thread is in its own stack of execution so it should be able to execute while tA is executing.
This is what Threads are for.
Generally speaking the answer is undefined. If your 'request' comes from remote client the answer depends on implementation details of the mechanism used for service exposing.
However, I'm not aware about remote communication frameworks that really make the proxy serializing the requests, i.e. that is assumed to be addressed by target service developer (e.g. its your task to provide thread-safety for the service implementation OR serialize all requests using explicit synchronization etc).