简体   繁体   中英

Java - How do I get or create a connection from multiple threads

I am trying to write a code that will ensure that I have a single connection object to all thread. In a singletone class I have the following member

MyConnection connection = null; 

And the written below get method does not support threads.
It tries to retrieve an open connection when none exists or if it was closed.

public Connection getConnection() throws IOException {

    while (connection == null || !connection.isOpen()) {

        MyConnectionInfo connectionInfo = getConnectionInfo();

        ConnectionFactory factory = new ConnectionFactory();
        ...

        connection = factory.newConnection();
    }
    return connection;
}

In this scenario I create one connection and before I assign it I can enter the loop for the second time.
How do I make it thread safe?
Is there a better option than surrounding blocks with synchronize (that will slow it down)?
Thanks.

I would use a synchronized block and then I would make sure MyConnection is thread safe. Don't make the code more complicated than it needs to be.

While synchronized does take time, it is trivial compared to what MyConnection is likely to do. By trivial I mean far less than 1/1000th of the time.

If you are really worried about performance, have more than one MyConnection as this is where the delay is likely to be.


Lets say your MyConnection connects via TCP to a service. This service takes 50 ms to respond. On the other hand, synchronized might take 500 ns if it is not optimised ie because you haven't called the code enough for it to JIT the code. This means the MyConnection is taking 100,000x times longer. Where do you think you should be spending your time optimising? ;)


Compare with say incrementing a counter like AtomicInteger.incrementAndGet() does. Even when warmed up the synchronzied might take 100 ns, but the add takes 5 ns. In this case synchronized is 20x slower and may be worth optimising eg by using AtomicInteger, if it is called enough, like millions of times.


In short, if you are doing any blocking IO operation, this will be so slow (and I mean many orders of magnitude slower) that one lock isn't going to make much difference esp if it saves you a random bug in your code.

You are not sharing connection between threads. Suppose first threads creates singleton instance but when second thread will try to get connection , first connection can be open so you create new connection. this breaks singleton pattern. Since you are creating new connection, who will take care of closing old connection.

Anyway you can synchronize whole method. As multiple threads are acquiring connections but connections are scarce resource you it's better option .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM