File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes JSP and the fly likes sorting table columns Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "sorting table columns" Watch "sorting table columns" New topic
Author

sorting table columns

saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
Hi I want to sort the employee table in jsp page
I got one soution for doing so but not sure whether this will be applicable in performance aspects

Please have a look at this code and tell me whether this can be used in my application.

I am developing one simple jsp,servlet,bean application ...


This is inside the servlet:



so for sorting logi I am using a bean called Emp and in that I am using some inner classes which implements comparator


Is it right solution for sorting the fields in the table?

Please suggest me if you have any good solutions for this..

Thanks,
Sai


A = HARDWORK B = LUCK/FATE If C=(A+B) then C=SUCCESSFUL IN LIFE else C=FAILURE IN LIFE
SCJP 1.4
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4167
    
  21

There is nothing particularly wrong with your code that would break it, but a couple of suggestions:
Try using a TreeSet to store the Employees. The TreeSet will sort the values as they get added to the Set, rather than as an after-wards. This may be more performant for large data sets, though probably not important for the small sample you have above (TreeSet.add = log(n), Collections.sort = n log(n)):


You would of course save more time by adding your employees directly into the Set rather than making an Array, turning an Array into a List, then adding the List to the Set, but I assume the array/Arrays.asList was a quick substitution for you Data Access Model (ie your employees are already coming to you in a List).

The second thing that I noticed is that you generate a new Comparator for each call to getComparator. This is not really necessary, you really only need one which knows how to compare all values and chooses which comparison to make, or at most one of each type which you provide as static constants.


Again, this won't improve the speed appreciably unless this block of code is heavily used and could be further cleaned up to remove the if/else String comparisons, but I suspect the performance gain would still be minor so take this change more as a coding style lean towards fewer objects... and if you need more objects initialize them early and cache them so you don't have to create the objects every time the code is called.


Steve
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4167
    
  21

And now that I realize I am in the JSP forum, I will reneg a little more on the second approach. The code I posted about sharing the same Comparator is not thread safe. If you have multiple viewers trying to sort different ways my code would fail. Your original post was better, though I would still recommend you cache the instances of each type of comparator so you don't have to re-create them all the time (I know they won't be super expensive to create, but if you can avoid it you probably should).
saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
You code is really nice in terms of avoiding inner class object creation each time when user sends a request to sort.

I dont why you are saying it is not applicable for thread safe applications.Is there any problem inside the bean?

saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
Yes, you are right creating inner class objects are not super expensive but still we can refine it to singleton objects for these classes...

Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4167
    
  21

Originally posted by saikrishna cinux:
You code is really nice in terms of avoiding inner class object creation each time when user sends a request to sort.

I dont why you are saying it is not applicable for thread safe applications.Is there any problem inside the bean?



The problem is that I have the Comparator stored as a static reference in the Emp class, so all Emp objects share the same comparator. I then store the String used to identify what to compare as an instance member of the Comparator. All users will see the same Comparator and the same instance variable. So if I go onto your site and try to sort by Name and at the same time you are on the site and try to sort by ID then we may see each other's sorting request, which is a bad thing.

I guess to overcome this you could store the compareWith reference as a ThreadLocal variable:
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4167
    
  21

Originally posted by saikrishna cinux:
Yes, you are right creating inner class objects are not super expensive but still we can refine it to singleton objects for these classes...


Hi Saikrishna,

That is a good way to get individual objects without having to re-create them. But just to be clear, the technique you showed is a form of Caching, not an example of Singletons. The Cache approach allows multiple instances of the same class to exist but will store certain instance(s) for use later on. Cache is the appropriate tool to use, I just wanted to make sure you knew that the Singleton pattern is a bit more involved than what you showed.
saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
Hi Steve,
when you say caching, is there only one way to achive this ?
why dont you accept it as single ton too?
because i'll be using only one object of that particular inner class which is associated to that bean(EMP)

Please, if you dont mind can you please explain me more about caching technique.

1.what are the ways to achive caching? Do i need to create only inner class singleton objects for achiving caching?

2. is there any other way to achive?

3. If caching is implemented in the application for loading millions of records from database it may take more time and more memory(heap) ...

4. when do you think this is the best solution for designing an applciation?




:p hoping for best answers from you,steve.

Thanks
Sai
Sivaraman Lakshmanan
Ranch Hand

Joined: Aug 02, 2003
Posts: 231
Hi Saikrishna,
Do you really want to go back to the server for doing the sorting? If this is just a sorting in the JSP page then go for javascript where a simple scirpt class used in the table tag will solve the problem.

Hope this helps.


Regards,
Sivaraman.L
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4167
    
  21

Originally posted by saikrishna cinux:
Hi Steve,
when you say caching, is there only one way to achive this ?


There are many different ways to cache an object. You are caching an object to a static class member, which is great for small number of objects to be reached quickly. Other ways include serializing, storing inside a Map of some sort, and there are Caching frameworks out there that let you cache to local memory then store to more persistent media when memory runs low or last-access-time times out.


Originally posted by saikrishna cinux:
why dont you accept it as single ton too?
because i'll be using only one object of that particular inner class which is associated to that bean(EMP)


A Singleton is an object that follows a very specific design pattern that makes it so you CAN have ONLY one object of that type created. You do have only one object of the type created, but you COULD have more if you continue to call new EmpFirstNameComparator() a few more times - or if you give the code to me and I call new EmpFirstNameComparator(). You should read This Wikipedia Page to learn more. By the way - the comparators in this case do not need to be Singletons, and so should NOT be made into Singletons. Don't over-use the Singleton Pattern.

Originally posted by saikrishna cinux:
Please, if you dont mind can you please explain me more about caching technique.

1.what are the ways to achive caching? Do i need to create only inner class singleton objects for achiving caching?


No, As a matter of fact there is usually no need to cache singletons. You use a Cache to store frequently used objects that don't change much so that you don't have to make them all the time. This is especially important if creating those objects is costly and the code that uses them has heavy traffic - which could then cause a bottle neck. A singleton can be created only once, so you don't need to build a Cache to get it, just call the Singleton's getInstance() method. In a sense, the Singleton is a self-caching Object.


Originally posted by saikrishna cinux:
2. is there any other way to achive?


Yes, to a database, to serialized objects, to a Map instead of several instance variables ... there are as many ways to implement a Cache as there is to store objects. The key is to make sure that accessing the Cache is quicker than re-making the object.

Originally posted by saikrishna cinux:
3. If caching is implemented in the application for loading millions of records from database it may take more time and more memory(heap) ...


Yes. The trade of with Cache is you spend more Memory to hold the objects in exchange for quicker responses to requests for the object. There are 2 different kinds of Cache's I can think of, which I call the preemptive cache and the lazy cache. A Preemptive Cache will actively search for objects to make and store for later use. Because the objects are expensive to make then Caching up front like this can take a lot of time, but we may be willing to spend all this extra time now so we get quick responsiveness later, like for instance if we are making a game it is good to cache all the graphics we can up front, so when they come into play we done have a slow down as the graphic gets pulled from wherever it is stored. In the Comparator example above you used this preemptive caching technique.

The Lazy Cache waits for an object to be requested and made for the first time, it then stores it so later on it can be accessed much quicker. Here you get quicker start-up times and lower memory consumption at the start of the application, while your first access to data may be slow, later access will be quick. An example of when to use this would be if you perform searches over a database. You search and store the results, next time someone does the same search, the Cache would check to see if the DB was changed, and if not just return the Cached values. If we wanted to use Lazy Loading Cache in the Comparator example, it might look like this:


Of course for our Comparator application it doesn't really matter...

If you do have millions of objects coming from a DB, then you would have to be memory conscious about storing your cache. A few ways to help you out with this would be to store the most frequently used objects in a memory cache (or the last, 1000 objects referenced). Then use serialization to store other objects into a BLOB in a special DB table, or use a DB View Table that was designed to hold the results of a specific Query, so you can do a select all on it without making the DB filter a larger data set.

Also, if caching from a DB then it is a good idea to keep track of times when Caches were made, and each time the cache is accessed query the DB for last change time so you know if the data you are retrieving is up to date. You don't want to be giving out old data.

Finally, with memory intensive Caches you should implement a time out strategy. If the object hasn't been used in a while, let it die and get garbage collected. These Caches may have tiers of storage.
1) Newly Cached items get stored as normal references
2) Items not accessed in a while get moved to Soft References
SoftReferences will be collected when the gc() needs memory, but are not the priority for cleanup. You would guarantee that the older items get cleaned when memory gets low, but generally keep them alive when you have enough memory to work with.

Originally posted by saikrishna cinux:
4. when do you think this is the best solution for designing an applciation?


Depends entirely on the application. You should do a google search. There are several Frameworks that will help you add Caching to your application, and many articles that talk about strategies and design aspects. For example, a Cache should be invisible to the class trying to get a hold of an object, so a Cache is usually implemented is conjunction with a Factory Pattern on the Data Access Tier.
[ October 15, 2008: Message edited by: Steve Luke ]
saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
Originally posted by Sivaraman Lakshmanan:
Hi Saikrishna,
Do you really want to go back to the server for doing the sorting? If this is just a sorting in the JSP page then go for javascript where a simple scirpt class used in the table tag will solve the problem.

Hope this helps.


Actually there is no restriction for sorting the table data
but client side if I do this sorting I may need to use ajax or somethign else...
I am not aware of ajax...
Please can you tell me if anyjhting i can do with in client side?

thanks
Sai
saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
Wondeful Steve!!!

Thanks for giving so much knowlwdge on caching techniques ....
I will be searching it in google for exisiting frame works in google...

and one more question Steve.

So in the place of caching can we use hibernate concept?
 
wood burning stoves
 
subject: sorting table columns
 
Similar Threads
Sorting String List
How to Use Comparator or BeanPropertyUtil to sort by multiple criteria
Comparable and Comparator
Sorting by 3 variables dynamically in arrayList
help solving dynamic method invocation exception.