Reputation: 321
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 ?
Upvotes: 0
Views: 1121
Reputation: 2075
1)
2)
Upvotes: 3
Reputation: 116918
#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.
Upvotes: 0
Reputation: 40395
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.
Upvotes: 0
Reputation: 88826
There are advantages and disadvantages to using static methods:
Advantages:
Disadvantages:
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.
Upvotes: 0