Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > de.comp.lang.java > #13127
| From | "Christian H. Kuhn" <qno-news@qno.de> |
|---|---|
| Newsgroups | de.comp.lang.java |
| Subject | Thread-safe singleton |
| Date | 2017-09-06 18:29 +0200 |
| Message-ID | <f1am3bF8aciU1@mid.individual.net> (permalink) |
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
Back to de.comp.lang.java | Previous | Next — Next in thread | Find similar
Thread-safe singleton "Christian H. Kuhn" <qno-news@qno.de> - 2017-09-06 18:29 +0200
Re: Thread-safe singleton Patrick Roemer <sangamon@netcologne.de> - 2017-09-06 21:06 +0200
Re: Thread-safe singleton v_borchert@despammed.com (Volker Borchert) - 2017-09-06 20:02 +0000
Re: Thread-safe singleton Patrick Roemer <sangamon@netcologne.de> - 2017-09-06 23:27 +0200
Re: Thread-safe singleton v_borchert@despammed.com (Volker Borchert) - 2017-09-07 16:45 +0000
Re: Thread-safe singleton "Christian H. Kuhn" <qno-news@qno.de> - 2017-09-11 01:08 +0200
Re: Thread-safe singleton Patrick Roemer <sangamon@netcologne.de> - 2017-09-11 18:14 +0200
Re: Thread-safe singleton Marcel Mueller <news.5.maazl@spamgourmet.org> - 2017-09-06 23:26 +0200
Re: Thread-safe singleton Claus Reibenstein <4spamersonly@kabelmail.de> - 2017-09-10 13:52 +0200
csiph-web