reinventing the wheel : connection pool
As a learning experience I am in the process of creating sort of an jdbc connection pool class for my java/jsf application. It's just to play around. I'm sure there are much more sophisticated ways to handle this.
@ManagedBean(name = "pooltje", eager = true)
@ApplicationScoped
public class pooltje {
private Integer max_connecties = 10;
private connectie[] pool = new connectie[max_connecties];
public pooltje() {
for (Integer teller = 0; teller < max_connecties; teller++) {
pool[teller] = new connectie();
}
}
public Synchronzed Connection borrow() {
Connection ret_con = null;
while (ret_con == null) {
for (Integer t = 0; t < max_connecties; t++) {
if (pool[t].getUsed() == Boolean.FALSE && ret_con == null) {
ret_con = pool[t].getConn();
pool[t].setUsed(Boolean.TRUE);
}
}
}
return ret_con;
}
public synchronized void giveback(Connection terug) {
for (Integer t = 0; t < max_connecties; t++) {
if (pool[t].getConn() == terug) {
pool[t].setUsed(Boolean.FALSE);
}
}
}
}
I made the class a managed bean with application scope, so I开发者_开发百科 know it will be instantiated only once at startup of the application.
My actual question is, how can I call the borrow and giveback method. For the method borrow() I found the following:
FacesContext fc2 = FacesContext.getCurrentInstance();
Application app = fc2.getApplication();
Connection conn = (Connection) app.evaluateExpressionGet(fc2, "#{pooltje.borrow()}", Connection.class);
This works fine, however I feel that it should/could be easier. At least I do get a connection passed back.
For the method giveback() I have to pass a variable (the connection not to use anymore). How can I accomplish this?
The connection pool approach aside (or I would totally waste time doing a writeup along with detailed examples :/ ), you could just access other managed beans from inside a managed bean by injecting them as @ManagedProperty
.
@ManagedBean
@RequestScoped
public class ArbitraryBean {
@ManagedProperty("pooltje")
private Pooltje pooltje;
// ... Add at least a setter for it.
}
This way you can just access it in your @PostConstruct
or action methods whenever necessary:
public void doSomething() {
Connection connection = pooltje.borrow();
// ...
}
But really, a connection pool shouldn't be a JSF managed bean, and also not be designed that way. I basically entered this answer with my jaw wide open all the time .. I recommend to explore some existing open source connection pool libraries, such as BoneCP, if your sole purpose is to learn by example/exercise.
精彩评论