Static objects and concurrency in a web application
Posted
by
Ionut
on Programmers
See other posts from Programmers
or by Ionut
Published on 2012-05-05T11:17:49Z
Indexed on
2012/12/20
11:12 UTC
Read the original article
Hit count: 563
I'm developing small Java Web Applications on Tomcat server and I'm using MySQL as my database.
Up until now I was using a connection singleton for accessing the database but I found out that this will ensure just on connection per Application and there will be problems if multiple users want to access the database in the same time. (They all have to make us of that single Connection object). I created a Connection Pool
and I hope that this is the correct way of doing things.
Furthermore it seems that I developed the bad habit of creating a lot of static object and static methods (mainly because I was under the wrong impression that every static object will be duplicated for every client which accesses my application).
Because of this all the Service Classes ( classes used to handle database data) are static and distributed through a ServiceFactory
:
public class ServiceFactory {
private static final String JDBC = "JDBC";
private static String impl;
private static AccountService accountService;
private static BoardService boardService;
public static AccountService getAccountService(){
initConfig();
if (accountService == null){
if (impl.equalsIgnoreCase(JDBC)){
accountService = new JDBCAccountService();
}
}
return accountService;
}
public static BoardService getBoardService(){
initConfig();
if (boardService == null){
if (impl.equalsIgnoreCase(JDBC)){
boardService = new JDBCBoardService();
}
}
return boardService;
}
private static void initConfig(){
if (StringUtil.isEmpty(impl)){
impl = ConfigUtil.getProperty("service.implementation");
// If the config failed initialize with standard
if (StringUtil.isEmpty(impl)){
impl = JDBC;
}
}
}
This was the factory class which, as you can see, allows just one Service to exist at any time. Now, is this a bad practice? What happens if let's say 1k users access AccountService
simultaneously?
I know that all this questions and bad practices come from a bad understanding of the static attribute in a web application and the way the server handles this attributes. Any help on this topic would be more than welcomed. Thank you for your time!
© Programmers or respective owner