简体   繁体   English

Java-如何从多个线程获取或创建连接

[英]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. 并且下面编写的get方法不支持线程。
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. 我将使用同步块,然后确保MyConnection是线程安全的。 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. 尽管同步确实需要时间,但与MyConnection可能要做的相比,这是微不足道的。 By trivial I mean far less than 1/1000th of the time. 我所说的琐碎时间远远少于1/1000。

If you are really worried about performance, have more than one MyConnection as this is where the delay is likely to be. 如果您真的担心性能,请使用多个MyConnection,因为这可能会导致延迟。


Lets say your MyConnection connects via TCP to a service. 假设您的MyConnection通过TCP连接到服务。 This service takes 50 ms to respond. 该服务需要50毫秒才能响应。 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. 另一方面,如果未优化同步,则同步可能要花费500 ns,即因为您尚未调用足够的代码来使它JIT代码。 This means the MyConnection is taking 100,000x times longer. 这意味着MyConnection花费的时间是100,000倍。 Where do you think you should be spending your time optimising? 您认为应该在哪里花时间优化? ;) ;)


Compare with say incrementing a counter like AtomicInteger.incrementAndGet() does. 与说像AtomicInteger.incrementAndGet()这样的增加计数器进行比较。 Even when warmed up the synchronzied might take 100 ns, but the add takes 5 ns. 即使预热了,同步也可能需要100 ns,但加法需要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. 在这种情况下,同步速度要慢20倍,并且可能值得优化,例如使用AtomicInteger(如果已被调用得足够多的话,例如数百万次)。


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. 简而言之,如果您正在执行任何阻塞的IO操作,这将非常慢(并且我的意思是要慢许多个数量级),以至于如果一个锁在代码中保存了一个随机错误,则不会产生很大的不同,特别是。

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 . 由于多个线程正在获取连接,但是连接是稀缺资源,因此这是更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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