I am using java to create an interface to connect to a database. Each time I want to make a call to the database I need to create new connections to the database, which would make calling the database say 10 times slow.
To avoid having to create new connections each time I want to call the database I have a java thread running that holds all of the connection information.
To write/read from the database I want to create a thread that uses the connection information stored in the thread that’s already running, use it to execute specified read/write functions, and then exit.
However I am having trouble accessing this information from the thread which is already running. What would be the best way to accomplish this?
Why do you need a thread running to keep your connection open, just store it somewhere and execute queries as soon as you need it.. should it work?
In any case if you really want a thread you should care about having a synchronized collection (check
Collections.asSynchronizedList) that can be accessed and managed from your thread and others too.To overcome visibility problems just declare it as a
static finalvariable, so you won’t have any problems in accessing it from outside the thread you declared it into.Another easy solution (since connection seems to be not thread-safe) is not to use a thread but use just a monitor: you can easily manage a
wait()/notify()mechanism for which a thread that wants to execute a query checks if connection is “free”. if it is occupies the monitor and do whatever it wants before notifying all waiting threads.