Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: "Christian H. Kuhn" Newsgroups: de.comp.lang.java Subject: Thread-safe singleton Date: Wed, 6 Sep 2017 18:29:33 +0200 Lines: 63 Message-ID: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit X-Trace: individual.net vo3X06KEL91KPkjz1tSlJwWVJ6Vz5B9yozdYfrGPwoHgHUZ+Y= Cancel-Lock: sha1:bSkztPAuN2CRXgcyA4OjH5GGogk= X-Mozilla-News-Host: snews://news.individual.net:563 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Thunderbird/52.3.0 Xref: csiph.com de.comp.lang.java:13127 Hallo Gemeinde, Ich dachte, ich hätte das mit der Thread-Sicherheit inzwischen verstanden. PMD widerspricht mir. final class QFdsbDatabase { private static volatile Connection connection; private static final String DATABASE = "database"; /** * Private constructor to avoid instantiation. */ private QFdsbDatabase() { // empty } /** * Creates a Connection to a FIDE/DSB database and stores it in a static field for use. Access data is given by an * ini4j ini file. * * @return Connection to a FIDE/DSB database. * @throws QFdsbException * Exception */ static Connection getConnection() throws QFdsbException { if (null == connection) { synchronized (connection) { if (null == connection) { [... Daten aus ini4j-File, dataSource erstellen ... ] 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. Andere Frage: Wird die Connection nicht am Ende schon durch den impliziten finally-Block geschlossen, bevor sie ausgeliefert wird? TIA QNo