Path: csiph.com!news.mixmin.net!newsreader4.netcologne.de!news.netcologne.de!.POSTED.xdsl-89-0-92-227.netcologne.de!not-for-mail From: Patrick Roemer Newsgroups: de.comp.lang.java Subject: Re: Thread-safe singleton Date: Wed, 6 Sep 2017 21:06:25 +0200 Organization: news.netcologne.de Distribution: world Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Injection-Date: Wed, 6 Sep 2017 19:06:25 +0000 (UTC) Injection-Info: newsreader4.netcologne.de; posting-host="xdsl-89-0-92-227.netcologne.de:89.0.92.227"; logging-data="18802"; mail-complaints-to="abuse@netcologne.de" User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.24) Gecko/20100411 Thunderbird/2.0.0.24 Mnenhy/0.7.6.0 X-Mozilla-News-Host: news://news.netcologne.de In-Reply-To: Content-Language: en-US Xref: csiph.com de.comp.lang.java:13129 Responding to Christian H. Kuhn: > private static volatile Connection connection; [...] > static Connection getConnection() throws QFdsbException { > > if (null == connection) { > synchronized (connection) { > if (null == connection) { Wenn connection null ist, synchronisierst Du darüber? O_o > try (Connection myConnection = > dataSource.getConnection()) { > myConnection.setAutoCommit(true); > connection = myConnection; > } catch (SQLException e) { > throw new QFdsbException("Problems while opening > or closing JDBC Connection to player database", > e); > } > } > } > } > return connection; > } > > Lazy initialization der statischen Variablen, weil ich die geworfenen > Exceptions sehen will, sonst hätte ich einen static block genommen. Mit> einem intitialization-on-demand holder vertage ich das Problem in eine > Unterklasse. Double-checked locking sollte funktionieren, PMD behauptet > das Gegenteil. Das da oben funktioniert sicher nicht. Vergiss coole Pseudo-Optimierungen wie DCL einfach mal. Warum willst Du überhaupt eine Connection irgendwo statisch rumhängen lassen? > Andere Frage: Wird die Connection nicht am Ende schon durch den > impliziten finally-Block geschlossen, bevor sie ausgeliefert wird? Ja. Viele Grüße, Patrick