pg.ddx.io pgsql-jdbc@postgresql.org mailing list archive
help / color / mirror / Atom feedRe: performance problem of Failover Datasource?
13+ messages / 5 participants
[nested] [flat]
* Re: performance problem of Failover Datasource?
@ 2012-12-13 10:42 Chen Huajun <chenhj@cn.fujitsu.com>
0 siblings, 1 reply; 13+ messages in thread
From: Chen Huajun @ 2012-12-13 10:42 UTC (permalink / raw)
To: kaprikorn07 <bharath.spyk@gmail.com>; +Cc: pgsql-jdbc
Hi All,
In the latest jdbc driver,multi backends can be assigned in the URL as following.
>With latest jdbc drivers you can simply configure multiple host:port pairs in the url separated by comma:
>jdbc:postgresql://host1:port1,host2:port2/test
>It has only the most basic failover support. When a new connection is opened the hosts are tried in round-robin until a connection is successfully established.
But there is a performance problem .if the first host is down,
all connecting must be blocked until connect timeout at first,
and then try connect to the next host.
Why not adjust the order of hosts dynamically?
For excample, after a successful connecting,if the target host is not the first host,
swap the target host and the first host.
And then subsequent connecting will try the most suitable host at first.
--
Best Regards,
Chen Huajun
(2012/12/12 17:09), kaprikorn07 wrote:
> Hi All,
>
> As Bruce Adams has mentioned, please let me know if there is any other way
> to do it other than pgBouncer and pgPool.
>
> Please help!
>
>
>
> --
> View this message in context: http://postgresql.1045698.n5.nabble.com/Re-Failover-Datasource-tp4496411p5736270.html
> Sent from the PostgreSQL - jdbc mailing list archive at Nabble.com.
>
>
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
^ permalink raw reply [nested|flat] 13+ messages in thread
* Re: performance problem of Failover Datasource?
@ 2012-12-13 21:01 Dave Cramer <pg@fastcrypt.com>
parent: Chen Huajun <chenhj@cn.fujitsu.com>
0 siblings, 1 reply; 13+ messages in thread
From: Dave Cramer @ 2012-12-13 21:01 UTC (permalink / raw)
To: Chen Huajun <chenhj@cn.fujitsu.com>; +Cc: kaprikorn07 <bharath.spyk@gmail.com>; pgsql-jdbc
Feel free to send us a patch.
Dave
Dave Cramer
dave.cramer(at)credativ(dot)ca
http://www.credativ.ca
On Thu, Dec 13, 2012 at 6:42 AM, Chen Huajun <chenhj@cn.fujitsu.com> wrote:
> Hi All,
>
>
> In the latest jdbc driver,multi backends can be assigned in the URL as
> following.
>
> >With latest jdbc drivers you can simply configure multiple host:port
> pairs in the url separated by comma:
> >jdbc:postgresql://host1:**port1,host2:port2/test
> >It has only the most basic failover support. When a new connection is
> opened the hosts are tried in round-robin until a connection is
> successfully established.
>
> But there is a performance problem .if the first host is down,
> all connecting must be blocked until connect timeout at first,
> and then try connect to the next host.
>
> Why not adjust the order of hosts dynamically?
> For excample, after a successful connecting,if the target host is not the
> first host,
> swap the target host and the first host.
> And then subsequent connecting will try the most suitable host at first.
>
>
> --
> Best Regards,
> Chen Huajun
> (2012/12/12 17:09), kaprikorn07 wrote:
>
>> Hi All,
>>
>> As Bruce Adams has mentioned, please let me know if there is any other way
>> to do it other than pgBouncer and pgPool.
>>
>> Please help!
>>
>>
>>
>> --
>> View this message in context: http://postgresql.1045698.n5.**
>> nabble.com/Re-Failover-**Datasource-tp4496411p5736270.**html<http://postgresql.1045698.n5.nabble.com/Re-Failover-Datasource-tp4496411p5736270.html;
>> Sent from the PostgreSQL - jdbc mailing list archive at Nabble.com.
>>
>>
>>
>
>
>
> --
> Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
> To make changes to your subscription:
> http://www.postgresql.org/**mailpref/pgsql-jdbc<http://www.postgresql.org/mailpref/pgsql-jdbc;
>
^ permalink raw reply [nested|flat] 13+ messages in thread
* Re: performance problem of Failover Datasource?
@ 2012-12-14 02:57 Chen Huajun <chenhj@cn.fujitsu.com>
parent: Dave Cramer <pg@fastcrypt.com>
0 siblings, 1 reply; 13+ messages in thread
From: Chen Huajun @ 2012-12-14 02:57 UTC (permalink / raw)
To: Dave Cramer <pg@fastcrypt.com>; +Cc: kaprikorn07 <bharath.spyk@gmail.com>; pgsql-jdbc
> Feel free to send us a patch.
OK,I will make the patch soon.
--
Best Regards,
Chen Huajun
(2012/12/14 5:01), Dave Cramer wrote:
> Feel free to send us a patch.
>
> Dave
>
> Dave Cramer
>
> dave.cramer(at)credativ(dot)ca
> http://www.credativ.ca
>
>
>
> On Thu, Dec 13, 2012 at 6:42 AM, Chen Huajun <chenhj@cn.fujitsu.com <mailto:chenhj@cn.fujitsu.com>> wrote:
>
> Hi All,
>
>
> In the latest jdbc driver,multi backends can be assigned in the URL as following.
>
> >With latest jdbc drivers you can simply configure multiple host:port pairs in the url separated by comma:
> >jdbc:postgresql://host1: port1,host2:port2/test
> >It has only the most basic failover support. When a new connection is opened the hosts are tried in round-robin until a connection is successfully established.
>
> But there is a performance problem .if the first host is down,
> all connecting must be blocked until connect timeout at first,
> and then try connect to the next host.
>
> Why not adjust the order of hosts dynamically?
> For excample, after a successful connecting,if the target host is not the first host,
> swap the target host and the first host.
> And then subsequent connecting will try the most suitable host at first.
>
>
> --
> Best Regards,
> Chen Huajun
> (2012/12/12 17:09), kaprikorn07 wrote:
>
> Hi All,
>
> As Bruce Adams has mentioned, please let me know if there is any other way
> to do it other than pgBouncer and pgPool.
>
> Please help!
>
>
>
> --
> View this message in context: http://postgresql.1045698.n5. nabble.com/Re-Failover- Datasource-tp4496411p5736270. html
> <http://postgresql.1045698.n5.nabble.com/Re-Failover-Datasource-tp4496411p5736270.html;
> Sent from the PostgreSQL - jdbc mailing list archive at Nabble.com.
>
>
>
>
>
>
> --
> Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org <mailto:pgsql-jdbc@postgresql.org>)
> To make changes to your subscription:
> http://www.postgresql.org/ mailpref/pgsql-jdbc <http://www.postgresql.org/mailpref/pgsql-jdbc;
>
>
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
^ permalink raw reply [nested|flat] 13+ messages in thread
* Re: performance problem of Failover Datasource?
@ 2012-12-14 13:29 Chen Huajun <chenhj@cn.fujitsu.com>
parent: Chen Huajun <chenhj@cn.fujitsu.com>
0 siblings, 1 reply; 13+ messages in thread
From: Chen Huajun @ 2012-12-14 13:29 UTC (permalink / raw)
To: Dave Cramer <pg@fastcrypt.com>; +Cc: kaprikorn07 <bharath.spyk@gmail.com>; pgsql-jdbc
Hi
I had make the patch,Please check it.
and I had run the testcases,the result is same as before modified.
--
Best Regards,
Chen Huajun
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
Attachments:
pgjdbc_optimization_for_mutiServerUrl.patch (text/plain, 3.4K) download
diff --git a/org/postgresql/core/ConnectionFactory.java b/org/postgresql/core/ConnectionFactory.java
index a351619..e2ba588 100644
--- a/org/postgresql/core/ConnectionFactory.java
+++ b/org/postgresql/core/ConnectionFactory.java
@@ -8,7 +8,10 @@
*/
package org.postgresql.core;
+import java.util.Collections;
+import java.util.HashSet;
import java.util.Properties;
+import java.util.Set;
import java.sql.SQLException;
import org.postgresql.util.HostSpec;
@@ -32,6 +35,11 @@
{ "3", new org.postgresql.core.v3.ConnectionFactoryImpl() },
{ "2", new org.postgresql.core.v2.ConnectionFactoryImpl() },
};
+
+ /**
+ * List of alive servers.
+ */
+ private static final Set<String> aliveServers = Collections.synchronizedSet(new HashSet<String>());
/**
* Establishes and initializes a new connection.
@@ -54,6 +62,12 @@
public static ProtocolConnection openConnection(HostSpec[] hostSpecs, String user, String database, Properties info, Logger logger) throws SQLException {
String protoName = info.getProperty("protocolVersion");
+ // Adjust the order of hostSpecs to try the most suitable server first.
+ if(hostSpecs.length > 1)
+ {
+ hostSpecs = adjustHostSpecsOrder(hostSpecs);
+ }
+
for (int i = 0; i < versions.length; ++i)
{
String versionProtoName = (String) versions[i][0];
@@ -62,10 +76,30 @@
ConnectionFactory factory = (ConnectionFactory) versions[i][1];
ProtocolConnection connection = factory.openConnectionImpl(hostSpecs, user, database, info, logger);
- if (connection != null)
- return connection;
+ if (connection != null) {
+ if (hostSpecs.length > 1) {
+ String hostSpecKey = connection.getHostSpec().toString();
+
+ // Remove servers which can not be connected from the list of alive servers
+ for (int j = 0; j < hostSpecs.length; j++) {
+ if (hostSpecKey.equals(hostSpecs[j].toString()))
+ break;
+
+ aliveServers.remove(hostSpecs[j].toString());
+ }
+ // Add the current server to the list of alive servers
+ aliveServers.add(hostSpecKey);
+ }
+ return connection;
+ }
}
+ if (hostSpecs.length > 1) {
+ // Remove servers which can not be connected from the list of alive servers
+ for (int j = 0; j < hostSpecs.length; j++) {
+ aliveServers.remove(hostSpecs[j].toString());
+ }
+ }
throw new PSQLException(GT.tr("A connection could not be made using the requested protocol {0}.", protoName),
PSQLState.CONNECTION_UNABLE_TO_CONNECT);
}
@@ -86,4 +120,26 @@
* than protocol version incompatibility.
*/
public abstract ProtocolConnection openConnectionImpl(HostSpec[] hostSpecs, String user, String database, Properties info, Logger logger) throws SQLException;
+
+
+ /**
+ * Adjust the order of servers in hostSpecs, internally move first found alive server to head.
+ */
+ private static HostSpec[] adjustHostSpecsOrder(HostSpec[] hostSpecs) {
+ if (aliveServers.isEmpty()
+ || aliveServers.contains(hostSpecs[0].toString()))
+ return hostSpecs;
+
+ HostSpec[] result = hostSpecs.clone();
+
+ for (int i = 1; i < hostSpecs.length; i++) {
+ if (aliveServers.contains(hostSpecs[i].toString())) {
+ result[0] = hostSpecs[i];
+ result[i] = hostSpecs[0];
+ break;
+ }
+ }
+
+ return result;
+ }
}=
^ permalink raw reply [nested|flat] 13+ messages in thread
* Re: performance problem of Failover Datasource?
@ 2012-12-15 07:10 Chen Huajun <chenhj@cn.fujitsu.com>
parent: Chen Huajun <chenhj@cn.fujitsu.com>
0 siblings, 1 reply; 13+ messages in thread
From: Chen Huajun @ 2012-12-15 07:10 UTC (permalink / raw)
To: Dave Cramer <pg@fastcrypt.com>; +Cc: kaprikorn07 <bharath.spyk@gmail.com>; pgsql-jdbc
Hi
In this patch,I use Collections.synchronizedSet to synchronize within multi-threads.
But i worry about locking operation is a litter frequent by Collections.synchronizedSet
and may affect performance.
I think using keword "synchronized" explicitly instead of Collections.synchronizedSet
may reduce times of locking.Is there any better suggestion?
In addition, I have a idea.
By adjusting the order of hosts we also can implement a simple load balance
while all of the hosts are master or read only slave.
For example:
Basically pick up the server randomly.If one server had dead remove it from the candidates,
and retry the next server.
And after a while(can be configured) re-add the dead host to the candidates because the dead
server may had been repaired.
What about that?
(2012/12/14 21:29), Chen Huajun wrote:
> Hi
>
> I had make the patch,Please check it.
>
> and I had run the testcases,the result is same as before modified.
>
>
>
>
>
--
Best Regards,
Chen Huajun
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
^ permalink raw reply [nested|flat] 13+ messages in thread
* Re: performance problem of Failover Datasource?
@ 2012-12-15 16:19 Scott Harrington <scotth01@sns-usa.com>
parent: Chen Huajun <chenhj@cn.fujitsu.com>
0 siblings, 2 replies; 13+ messages in thread
From: Scott Harrington @ 2012-12-15 16:19 UTC (permalink / raw)
To: pgsql-jdbc
On Sat, 15 Dec 2012, Chen Huajun wrote:
> In this patch,I use Collections.synchronizedSet to synchronize within
> multi-threads. But i worry about locking operation is a litter frequent
> by Collections.synchronizedSet and may affect performance. I think using
> keword "synchronized" explicitly instead of Collections.synchronizedSet
> may reduce times of locking.Is there any better suggestion?
>
> In addition, I have a idea. By adjusting the order of hosts we also can
> implement a simple load balance while all of the hosts are master or
> read only slave. For example: Basically pick up the server randomly.If
> one server had dead remove it from the candidates, and retry the next
> server. And after a while(can be configured) re-add the dead host to the
> candidates because the dead server may had been repaired.
>
> What about that?
Perhaps instead you could abstract this logic into a
org.postgresql.util.HostChooser interface, which would replace the
HostSpec[] array that currently gets passed around.
Something like this, which doesn't require synchronization but rather
stores a single volatile index of the "last known good" server address
(warning: coding off the top of my head).
public interface HostChooser implements Iterable<HostSpec> {
Iterator<HostSpec> iterator();
void reportSuccessfulConnection(HOstSpec hostSpec);
}
public class SingleHostChooser implements HostChooser
{
private final HostSpec hostSpec;
public SingleHostChooser(HostSpec hostSpec) { this.hostSpec = hostSpec; }
public Iterator<HostSpec> iterator() { return Collections.singletonList(hostSpec).iterator(); }
public void reportSuccessfulConnection(HostSpec ignored) {}
}
public class LastKnownGoodHostChooser implements HostChooser
{
private final HostSpec[] hostSpecs;
private volatile int lastKnownGood = -1;
public LastKnownGoodHostChooser(HostSpec[] hostSpecs) { this.hostSpecs = hostSpecs.clone(); }
public Iterator<HostSpec> iterator() {
int first = lastKnownGood;
if (first <= 0) {
return Arrays.asList(hostSpecs).iterator();
}
ArrayList<HostSpec> reordered = new ArrayList<HostSpec>(hostSpecs.length);
for (int ii = first; ii < hostSpecs.length; ++ii) {
reordered.add(hostSpecs[ii]);
}
for (int ii = 0; ii < first; ++ii) {
reordered.add(hostSpecs[ii]);
}
return reordered.iterator();
}
public void reportSuccessfulConnection(HostSpec hostSpec) {
lastKnownGood = Arrays.asList(hostSpecs).indexOf(hostSpec);
}
}
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
^ permalink raw reply [nested|flat] 13+ messages in thread
* Re: performance problem of Failover Datasource?
@ 2012-12-18 00:05 Chen Huajun <chenhj@cn.fujitsu.com>
parent: Scott Harrington <scotth01@sns-usa.com>
1 sibling, 1 reply; 13+ messages in thread
From: Chen Huajun @ 2012-12-18 00:05 UTC (permalink / raw)
To: Scott Harrington <scotth01@sns-usa.com>; +Cc: pgsql-jdbc
Thanks for you advise.
I will try to made a new patch and add load balance supporting.
--
Best Regards,
Chen Huajun
(2012/12/16 0:19), Scott Harrington wrote:
> On Sat, 15 Dec 2012, Chen Huajun wrote:
>
>> In this patch,I use Collections.synchronizedSet to synchronize within multi-threads. But i worry about locking operation is a litter frequent by Collections.synchronizedSet and may affect
>> performance. I think using keword "synchronized" explicitly instead of Collections.synchronizedSet may reduce times of locking.Is there any better suggestion?
>>
>> In addition, I have a idea. By adjusting the order of hosts we also can implement a simple load balance while all of the hosts are master or read only slave. For example: Basically pick up the
>> server randomly.If one server had dead remove it from the candidates, and retry the next server. And after a while(can be configured) re-add the dead host to the candidates because the dead server
>> may had been repaired.
>>
>> What about that?
>
> Perhaps instead you could abstract this logic into a org.postgresql.util.HostChooser interface, which would replace the HostSpec[] array that currently gets passed around.
>
> Something like this, which doesn't require synchronization but rather stores a single volatile index of the "last known good" server address (warning: coding off the top of my head).
>
> public interface HostChooser implements Iterable<HostSpec> {
> Iterator<HostSpec> iterator();
> void reportSuccessfulConnection(HOstSpec hostSpec);
> }
>
> public class SingleHostChooser implements HostChooser
> {
> private final HostSpec hostSpec;
> public SingleHostChooser(HostSpec hostSpec) { this.hostSpec = hostSpec; }
> public Iterator<HostSpec> iterator() { return Collections.singletonList(hostSpec).iterator(); }
> public void reportSuccessfulConnection(HostSpec ignored) {}
> }
>
> public class LastKnownGoodHostChooser implements HostChooser
> {
> private final HostSpec[] hostSpecs;
> private volatile int lastKnownGood = -1;
> public LastKnownGoodHostChooser(HostSpec[] hostSpecs) { this.hostSpecs = hostSpecs.clone(); }
>
> public Iterator<HostSpec> iterator() {
> int first = lastKnownGood;
> if (first <= 0) {
> return Arrays.asList(hostSpecs).iterator();
> }
> ArrayList<HostSpec> reordered = new ArrayList<HostSpec>(hostSpecs.length);
> for (int ii = first; ii < hostSpecs.length; ++ii) {
> reordered.add(hostSpecs[ii]);
> }
> for (int ii = 0; ii < first; ++ii) {
> reordered.add(hostSpecs[ii]);
> }
> return reordered.iterator();
> }
>
> public void reportSuccessfulConnection(HostSpec hostSpec) {
> lastKnownGood = Arrays.asList(hostSpecs).indexOf(hostSpec);
> }
> }
>
>
>
>
>
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
^ permalink raw reply [nested|flat] 13+ messages in thread
* Re: performance problem of Failover Datasource?
@ 2012-12-18 00:29 Craig Ringer <craig@2ndquadrant.com>
parent: Scott Harrington <scotth01@sns-usa.com>
1 sibling, 0 replies; 13+ messages in thread
From: Craig Ringer @ 2012-12-18 00:29 UTC (permalink / raw)
To: Scott Harrington <scotth01@sns-usa.com>; +Cc: pgsql-jdbc
On 16/12/2012 12:19 AM, Scott Harrington wrote:
> On Sat, 15 Dec 2012, Chen Huajun wrote:
>
>> In this patch,I use Collections.synchronizedSet to synchronize within
>> multi-threads. But i worry about locking operation is a litter
>> frequent by Collections.synchronizedSet and may affect performance. I
>> think using keword "synchronized" explicitly instead of
>> Collections.synchronizedSet may reduce times of locking.Is there any
>> better suggestion?
>>
>> In addition, I have a idea. By adjusting the order of hosts we also
>> can implement a simple load balance while all of the hosts are master
>> or read only slave. For example: Basically pick up the server
>> randomly.If one server had dead remove it from the candidates, and
>> retry the next server. And after a while(can be configured) re-add
>> the dead host to the candidates because the dead server may had been
>> repaired.
>>
>> What about that?
>
> Perhaps instead you could abstract this logic into a
> org.postgresql.util.HostChooser interface, which would replace the
> HostSpec[] array that currently gets passed around.
There's certainly value to that. We're almost certainly goin to want to
support things like connecting to any slave and asking it "which server
is the master I should connect to" in future, so a way to abstract host
selection would be a big win.
--
Craig Ringer http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
^ permalink raw reply [nested|flat] 13+ messages in thread
* Re: performance problem of Failover Datasource?
@ 2012-12-24 10:26 Chen Huajun <chenhj@cn.fujitsu.com>
parent: Chen Huajun <chenhj@cn.fujitsu.com>
0 siblings, 1 reply; 13+ messages in thread
From: Chen Huajun @ 2012-12-24 10:26 UTC (permalink / raw)
To: pgsql-jdbc
Hi
I have made a new patch(with my test). Please give a look.
It support the following features
1) performance improve for fail over by avoiding dead hosts.
2) simple load balance by picking up the first host from multiple valid hosts randomly.
3) ability of choosing master or slave to connect to.
And in the patch, three connection parameters were added.
targetServerType = String
Specifies what kind of server to connect.The value should be one of the following:
any
master
slave
slavefirst (Try connecting to the slaves first.If failed try the master)
The default is 'any'.
enableLoadBalance = boolean
Enable or disable load balance when multiple hosts were specified;If load balance is enabled,specified multiple hosts will be picked up randomly.
The default is false.
failedHostCheckPeriod = int
Specifies period(seconds) to check whether the failed hosts had been repaired, when load balance is enabled; 0 means never check.
The default is 600 seconds.
(2012/12/18 8:05), Chen Huajun wrote:
>
> Thanks for you advise.
> I will try to made a new patch and add load balance supporting.
>
>
--
Best Regards,
Chen Huajun
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
Attachments:
pgjdbc_failover_loadbalance_for_mutihosts.patch (text/plain, 28.6K) download
diff --git a/build.xml b/build.xml
index c9c5660..e34f85f 100644
--- a/build.xml
+++ b/build.xml
@@ -132,6 +132,7 @@
<include name="${package}/fastpath/**" />
<include name="${package}/geometric/**" />
<include name="${package}/largeobject/**" />
+ <include name="${package}/hostchooser/**" />
<include name="${package}/util/**" />
<!--
diff --git a/org/postgresql/Driver.java.in b/org/postgresql/Driver.java.in
index f6c69c0..3f9eacc 100644
--- a/org/postgresql/Driver.java.in
+++ b/org/postgresql/Driver.java.in
@@ -465,7 +465,14 @@
{ "kerberosServerName", Boolean.FALSE,
"The Kerberos service name to use when authenticating with GSSAPI. This is equivalent to libpq's PGKRBSRVNAME environment variable." },
{ "jaasApplicationName", Boolean.FALSE,
- "Specifies the name of the JAAS system or application login configuration." }
+ "Specifies the name of the JAAS system or application login configuration." },
+ { "targetServerType", Boolean.FALSE,
+ "Specifies what kind of server to connect.",
+ new String[] { "any", "master", "slave", "slavefirst" } },
+ { "enableLoadBalance", Boolean.FALSE,
+ "Enable or disable load balance when multiple hosts were specified;If load balance is enabled,specified multiple hosts will be picked up randomly."},
+ { "failedHostCheckPeriod", Boolean.FALSE,
+ "Specifies period(seconds) to check whether the failed hosts had been repaired, when load balance is enabled; 0 means never check." }
};
/**
diff --git a/org/postgresql/core/v2/ConnectionFactoryImpl.java b/org/postgresql/core/v2/ConnectionFactoryImpl.java
index a0cfc96..7935cc4 100644
--- a/org/postgresql/core/v2/ConnectionFactoryImpl.java
+++ b/org/postgresql/core/v2/ConnectionFactoryImpl.java
@@ -8,6 +8,7 @@
*/
package org.postgresql.core.v2;
+import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
@@ -17,6 +18,9 @@
import java.net.ConnectException;
import org.postgresql.core.*;
+import org.postgresql.hostchooser.HostChooser;
+import org.postgresql.hostchooser.HostChooserFactory;
+import org.postgresql.hostchooser.HostStatus;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.UnixCrypt;
@@ -69,9 +73,20 @@
// - the TCP keep alive setting
boolean requireTCPKeepAlive = (Boolean.valueOf(info.getProperty("tcpKeepAlive")).booleanValue());
+
+ // - the targetServerType setting
+ String targetServerType = info.getProperty("targetServerType","any").toLowerCase();
+ if (!"any".equals(targetServerType) &&
+ !"master".equals(targetServerType) &&
+ !"slave".equals(targetServerType) &&
+ !"slavefirst".equals(targetServerType)){
+ throw new PSQLException (GT.tr("Invalid targetServerType value: {0}", targetServerType), PSQLState.CONNECTION_UNABLE_TO_CONNECT);
+ }
- for (int whichHost = 0; whichHost < hostSpecs.length; ++whichHost) {
- HostSpec hostSpec = hostSpecs[whichHost];
+ HostChooser hostChooser = HostChooserFactory.createHostChooser(hostSpecs, info);
+ Iterator<HostSpec> hostIter = hostChooser.iterator();
+ while(hostIter.hasNext()) {
+ HostSpec hostSpec = hostIter.next();
if (logger.logDebug())
logger.debug("Trying to establish a protocol version 2 connection to " + hostSpec);
@@ -115,6 +130,41 @@
ProtocolConnectionImpl protoConnection = new ProtocolConnectionImpl(newStream, user, database, logger);
readStartupMessages(newStream, protoConnection, logger);
+ // Check Master or Slaver
+ if(targetServerType.equals("any")){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectOK);
+ }else if(targetServerType.equals("master")){
+ if(isMaster(protoConnection, logger)){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Master);
+ }else{
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Slave);
+ protoConnection.close();
+ if (hostIter.hasNext()) {
+ // still more addresses to try
+ continue;
+ }
+ throw new PSQLException (GT.tr("Couldn't find a server with specified targetServerType: {0}", targetServerType) , PSQLState.CONNECTION_UNABLE_TO_CONNECT);
+ }
+ }else if(targetServerType.equals("slave")){
+ if(isMaster(protoConnection, logger)){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Master);
+ protoConnection.close();
+ if (hostIter.hasNext()) {
+ // still more addresses to try
+ continue;
+ }
+ throw new PSQLException (GT.tr("Couldn't find a server with specified targetServerType: {0}", targetServerType) , PSQLState.CONNECTION_UNABLE_TO_CONNECT);
+ }else{
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Slave);
+ }
+ }else{//slaveFirst
+ if(isMaster(protoConnection, logger)){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Master);
+ }else{
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Slave);
+ }
+ }
+
// Run some initial queries
runInitialQueries(protoConnection, info, logger);
@@ -127,7 +177,8 @@
// ConnectException is thrown when the connection cannot be made.
// we trap this an return a more meaningful message for the end user
- if (whichHost + 1 < hostSpecs.length) {
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
+ if (hostIter.hasNext()) {
// still more addresses to try
continue;
}
@@ -146,7 +197,8 @@
}
}
- if (whichHost + 1 < hostSpecs.length) {
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
+ if (hostIter.hasNext()) {
// still more addresses to try
continue;
}
@@ -165,7 +217,8 @@
}
}
- if (whichHost + 1 < hostSpecs.length) {
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
+ if (hostIter.hasNext()) {
// still more addresses to try
continue;
}
@@ -401,7 +454,7 @@
}
}
}
-
+
private void runInitialQueries(ProtocolConnectionImpl protoConnection, Properties info, Logger logger) throws SQLException, IOException {
byte[][] results = SetupQueryRunner.run(protoConnection, "set datestyle = 'ISO'; select version(), case when pg_encoding_to_char(1) = 'SQL_ASCII' then 'UNKNOWN' else getdatabaseencoding() end", true);
@@ -485,4 +538,11 @@
SetupQueryRunner.run(protoConnection, sb.toString(), false);
}
}
+
+
+ private boolean isMaster(ProtocolConnectionImpl protoConnection, Logger logger)throws SQLException, IOException {
+ byte[][] results = SetupQueryRunner.run(protoConnection, "show transaction_read_only", true);
+ String value = protoConnection.getEncoding().decode(results[0]);
+ return value.equalsIgnoreCase("off");
+ }
}
diff --git a/org/postgresql/core/v3/ConnectionFactoryImpl.java b/org/postgresql/core/v3/ConnectionFactoryImpl.java
index 95eaa43..b4f4b0b 100644
--- a/org/postgresql/core/v3/ConnectionFactoryImpl.java
+++ b/org/postgresql/core/v3/ConnectionFactoryImpl.java
@@ -8,6 +8,7 @@
*/
package org.postgresql.core.v3;
+import java.util.Iterator;
import java.util.Properties;
import java.util.TimeZone;
@@ -16,6 +17,9 @@
import java.net.ConnectException;
import org.postgresql.core.*;
+import org.postgresql.hostchooser.HostChooser;
+import org.postgresql.hostchooser.HostChooserFactory;
+import org.postgresql.hostchooser.HostStatus;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.PSQLWarning;
@@ -78,6 +82,15 @@
// - the TCP keep alive setting
boolean requireTCPKeepAlive = (Boolean.valueOf(info.getProperty("tcpKeepAlive")).booleanValue());
+ // - the targetServerType setting
+ String targetServerType = info.getProperty("targetServerType","any").toLowerCase();
+ if (!"any".equals(targetServerType) &&
+ !"master".equals(targetServerType) &&
+ !"slave".equals(targetServerType) &&
+ !"slavefirst".equals(targetServerType)){
+ throw new PSQLException (GT.tr("Invalid targetServerType value: {0}", targetServerType), PSQLState.CONNECTION_UNABLE_TO_CONNECT);
+ }
+
// NOTE: To simplify this code, it is assumed that if we are
// using the V3 protocol, then the database is at least 7.4. That
// eliminates the need to check database versions and maintain
@@ -85,8 +98,10 @@
//
// Change by Chris Smith <cdsmith@twu.net>
- for (int whichHost = 0; whichHost < hostSpecs.length; ++whichHost) {
- HostSpec hostSpec = hostSpecs[whichHost];
+ HostChooser hostChooser = HostChooserFactory.createHostChooser(hostSpecs, info);
+ Iterator<HostSpec> hostIter = hostChooser.iterator();
+ while(hostIter.hasNext()) {
+ HostSpec hostSpec = hostIter.next();
if (logger.logDebug())
logger.debug("Trying to establish a protocol version 3 connection to " + hostSpec);
@@ -176,8 +191,43 @@
ProtocolConnectionImpl protoConnection = new ProtocolConnectionImpl(newStream, user, database, info, logger);
readStartupMessages(newStream, protoConnection, logger);
+ // Check Master or Slaver
+ if(targetServerType.equals("any")){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectOK);
+ }else if(targetServerType.equals("master")){
+ if(isMaster(protoConnection, logger)){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Master);
+ }else{
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Slave);
+ protoConnection.close();
+ if (hostIter.hasNext()) {
+ // still more addresses to try
+ continue;
+ }
+ throw new PSQLException (GT.tr("Couldn't find a server with specified targetServerType: {0}", targetServerType) , PSQLState.CONNECTION_UNABLE_TO_CONNECT);
+ }
+ }else if(targetServerType.equals("slave")){
+ if(isMaster(protoConnection, logger)){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Master);
+ protoConnection.close();
+ if (hostIter.hasNext()) {
+ // still more addresses to try
+ continue;
+ }
+ throw new PSQLException (GT.tr("Couldn't find a server with specified targetServerType: {0}", targetServerType) , PSQLState.CONNECTION_UNABLE_TO_CONNECT);
+ }else{
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Slave);
+ }
+ }else{//slaveFirst
+ if(isMaster(protoConnection, logger)){
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Master);
+ }else{
+ hostChooser.reportHostStatus(hostSpec, HostStatus.Slave);
+ }
+ }
+
runInitialQueries(protoConnection, info, logger);
-
+
// And we're done.
return protoConnection;
}
@@ -193,6 +243,7 @@
catch (IOException e)
{
}
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
return null;
}
catch (ConnectException cex)
@@ -200,7 +251,9 @@
// Added by Peter Mount <peter@retep.org.uk>
// ConnectException is thrown when the connection cannot be made.
// we trap this an return a more meaningful message for the end user
- if (whichHost + 1 < hostSpecs.length) {
+
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
+ if (hostIter.hasNext()) {
// still more addresses to try
continue;
}
@@ -218,7 +271,8 @@
{
}
}
- if (whichHost + 1 < hostSpecs.length) {
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
+ if (hostIter.hasNext()) {
// still more addresses to try
continue;
}
@@ -236,7 +290,8 @@
{
}
}
- if (whichHost + 1 < hostSpecs.length) {
+ hostChooser.reportHostStatus(hostSpec, HostStatus.ConnectFail);
+ if (hostIter.hasNext()) {
// still more addresses to try
continue;
}
@@ -646,5 +701,11 @@
}
}
+
+ private boolean isMaster(ProtocolConnectionImpl protoConnection, Logger logger)throws SQLException, IOException {
+ byte[][] results = SetupQueryRunner.run(protoConnection, "show transaction_read_only", true);
+ String value = protoConnection.getEncoding().decode(results[0]);
+ return value.equalsIgnoreCase("off");
+ }
}
diff --git a/org/postgresql/ds/common/BaseDataSource.java b/org/postgresql/ds/common/BaseDataSource.java
index bfe54f7..0a00e69 100644
--- a/org/postgresql/ds/common/BaseDataSource.java
+++ b/org/postgresql/ds/common/BaseDataSource.java
@@ -63,6 +63,9 @@
private int logLevel = 0;
private int protocolVersion = 0;
private String applicationName;
+ private String targetServerType;
+ private boolean enableLoadBalance = false;
+ private int failedHostCheckPeriod = -1;
/**
* Gets a connection to the PostgreSQL database. The database is identified by the
@@ -397,7 +400,37 @@
{
return applicationName;
}
+
+ public void setTargetServerType(String targetServerType)
+ {
+ this.targetServerType = targetServerType;
+ }
+
+ public String getTargetServerType()
+ {
+ return targetServerType;
+ }
+
+ public void setEnableLoadBalance(boolean enableLoadBalance)
+ {
+ this.enableLoadBalance = enableLoadBalance;
+ }
+ public boolean getEnableLoadBalance()
+ {
+ return enableLoadBalance;
+ }
+
+ public void setFailedHostCheckPeriod(int failedHostCheckPeriod)
+ {
+ this.failedHostCheckPeriod = failedHostCheckPeriod;
+ }
+
+ public int getFailedHostCheckPeriod()
+ {
+ return failedHostCheckPeriod;
+ }
+
public void setTcpKeepAlive(boolean enabled)
{
tcpKeepAlive = enabled;
@@ -513,6 +546,16 @@
if (binaryTransfer) {
sb.append("&binaryTransfer=true");
}
+ if (targetServerType != null) {
+ sb.append("&targetServerType=");
+ sb.append(targetServerType);
+ }
+ if (enableLoadBalance) {
+ sb.append("&enableLoadBalance=true");
+ }
+ if (failedHostCheckPeriod != -1) {
+ sb.append("&failedHostCheckPeriod=").append(failedHostCheckPeriod);
+ }
return sb.toString();
}
@@ -565,6 +608,10 @@
ref.add(new StringRefAddr("logLevel", Integer.toString(logLevel)));
ref.add(new StringRefAddr("protocolVersion", Integer.toString(protocolVersion)));
ref.add(new StringRefAddr("ApplicationName", applicationName));
+
+ ref.add(new StringRefAddr("targetServerType", targetServerType));
+ ref.add(new StringRefAddr("enableLoadBalance", Boolean.toString(enableLoadBalance)));
+ ref.add(new StringRefAddr("failedHostCheckPeriod", Integer.toString(failedHostCheckPeriod)));
return ref;
}
@@ -592,6 +639,9 @@
out.writeBoolean(binaryTransfer);
out.writeObject(binaryTransferEnable);
out.writeObject(binaryTransferDisable);
+ out.writeObject(targetServerType);
+ out.writeBoolean(enableLoadBalance);
+ out.writeInt(failedHostCheckPeriod);
}
protected void readBaseObject(ObjectInputStream in) throws IOException, ClassNotFoundException
@@ -617,6 +667,9 @@
binaryTransfer = in.readBoolean();
binaryTransferEnable = (String)in.readObject();
binaryTransferDisable = (String)in.readObject();
+ targetServerType = (String)in.readObject();
+ enableLoadBalance = in.readBoolean();
+ failedHostCheckPeriod = in.readInt();
}
public void initializeFrom(BaseDataSource source) throws IOException, ClassNotFoundException {
diff --git a/org/postgresql/hostchooser/HostChooser.java b/org/postgresql/hostchooser/HostChooser.java
new file mode 100644
index 0000000..fa1e1a9
--- /dev/null
+++ b/org/postgresql/hostchooser/HostChooser.java
@@ -0,0 +1,16 @@
+/**
+ *
+ */
+package org.postgresql.hostchooser;
+
+import java.util.Iterator;
+
+import org.postgresql.util.HostSpec;
+
+/**
+ *
+ */
+public interface HostChooser {
+ Iterator<HostSpec> iterator();
+ void reportHostStatus(HostSpec hostSpec, HostStatus hostStatus);
+}
diff --git a/org/postgresql/hostchooser/HostChooserFactory.java b/org/postgresql/hostchooser/HostChooserFactory.java
new file mode 100644
index 0000000..0cf4461
--- /dev/null
+++ b/org/postgresql/hostchooser/HostChooserFactory.java
@@ -0,0 +1,26 @@
+/**
+ *
+ */
+package org.postgresql.hostchooser;
+
+import java.util.Properties;
+import org.postgresql.util.HostSpec;
+
+/**
+ *
+ */
+public class HostChooserFactory {
+
+ public static HostChooser createHostChooser(HostSpec[] hostSpecs,Properties info){
+
+ if(hostSpecs.length==1){
+ return new SingleHostChooser(hostSpecs[0]);
+ }
+
+ if (Boolean.valueOf(info.getProperty("enableLoadBalance","false")).booleanValue()){
+ return new LoadBalanceHostChooser(hostSpecs,info);
+ }
+
+ return new LastKnownGoodHostChooser(hostSpecs,info);
+ }
+}
diff --git a/org/postgresql/hostchooser/HostChooserWithStatusReport.java b/org/postgresql/hostchooser/HostChooserWithStatusReport.java
new file mode 100644
index 0000000..f0756b4
--- /dev/null
+++ b/org/postgresql/hostchooser/HostChooserWithStatusReport.java
@@ -0,0 +1,48 @@
+package org.postgresql.hostchooser;
+
+import java.util.HashMap;
+
+import org.postgresql.util.*;
+
+/*
+ * Abstract class which implements host status reporting
+ *
+ * @author Chen Huajun (chenhj@cn.fujitsu.com)
+ */
+public abstract class HostChooserWithStatusReport implements HostChooser
+{
+ private static volatile HashMap<String,HostStatus> hostStatusCache = new HashMap<String,HostStatus>();
+
+ protected HashMap<String,HostStatus> hostStatusMap = (HashMap<String, HostStatus>) hostStatusCache.clone();
+
+ public void reportHostStatus(HostSpec hostSpec, HostStatus hostStatus) {
+ reportHostStatus(hostSpec.toString(),hostStatus);
+ }
+
+ private boolean needUpdateHostStatus(HostStatus oldHostStatus,HostStatus newHostStatus){
+ if(oldHostStatus == newHostStatus)
+ return false;
+
+ if(newHostStatus == HostStatus.ConnectOK){
+ if(oldHostStatus == HostStatus.Master ||
+ oldHostStatus == HostStatus.Slave)
+ return false;
+ }
+
+ return true;
+ }
+
+ public void reportHostStatus(String hostSpecKey, HostStatus hostStatus) {
+ HostStatus oldHostStatus = hostStatusCache.get(hostSpecKey);
+ if(needUpdateHostStatus(oldHostStatus, hostStatus)) {
+ synchronized(HostChooserWithStatusReport.class){
+ oldHostStatus = hostStatusCache.get(hostSpecKey);
+ if(needUpdateHostStatus(oldHostStatus, hostStatus)) {
+ HashMap<String,HostStatus> newHostStatusMap = (HashMap<String, HostStatus>) hostStatusCache.clone();
+ newHostStatusMap.put(hostSpecKey, hostStatus);
+ hostStatusCache=newHostStatusMap;
+ }
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/org/postgresql/hostchooser/HostStatus.java b/org/postgresql/hostchooser/HostStatus.java
new file mode 100644
index 0000000..42ba31c
--- /dev/null
+++ b/org/postgresql/hostchooser/HostStatus.java
@@ -0,0 +1,14 @@
+/**
+ *
+ */
+package org.postgresql.hostchooser;
+
+/**
+ *
+ */
+public enum HostStatus {
+ ConnectOK,
+ ConnectFail,
+ Master,
+ Slave
+}
diff --git a/org/postgresql/hostchooser/LastKnownGoodHostChooser.java b/org/postgresql/hostchooser/LastKnownGoodHostChooser.java
new file mode 100644
index 0000000..158757c
--- /dev/null
+++ b/org/postgresql/hostchooser/LastKnownGoodHostChooser.java
@@ -0,0 +1,75 @@
+package org.postgresql.hostchooser;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Properties;
+
+import org.postgresql.util.*;
+
+/*
+ * Pick up one known good host first and then try others
+ *
+ * @author Chen Huajun (chenhj@cn.fujitsu.com)
+ */
+public class LastKnownGoodHostChooser extends HostChooserWithStatusReport
+{
+ private final HostSpec[] hostSpecs;
+ private String targetServerType;
+
+ public LastKnownGoodHostChooser(HostSpec[] hostSpecs,Properties info) {
+ this.hostSpecs = hostSpecs;
+ targetServerType = info.getProperty("targetServerType", "any").toLowerCase();
+ }
+
+ public Iterator<HostSpec> iterator() {
+ int first = -1;
+ for (int i = 0; i < hostSpecs.length; i++) {
+ HostStatus hostStatus = hostStatusMap.get(hostSpecs[i].toString());
+ if(hostStatus != null){
+ if(targetServerType.equals("any") && hostStatus != HostStatus.ConnectFail){
+ first = i;
+ break;
+ }
+
+ if(targetServerType.equals("master") && hostStatus == HostStatus.Master){
+ first = i;
+ break;
+ }
+
+ if((targetServerType.equals("slave") || targetServerType.equals("slavefirst")) &&
+ hostStatus == HostStatus.Slave){
+ first = i;
+ break;
+ }
+ }
+ }
+
+ if(first == -1 && targetServerType.equals("slavefirst")){
+ for (int i = 0; i < hostSpecs.length; i++) {
+ HostStatus hostStatus = hostStatusMap.get(hostSpecs[i].toString());
+ if(hostStatus != null){
+ if(hostStatus != HostStatus.ConnectFail){
+ first = i;
+ break;
+ }
+ }
+ }
+ }
+
+ if (first == -1 ) {
+ first = 0;
+ }
+
+ ArrayList<HostSpec> reordered = new ArrayList<HostSpec>(hostSpecs.length);
+ for (int i = first; i < hostSpecs.length; i++) {
+ reordered.add(hostSpecs[i]);
+ }
+
+ for (int i = 0; i < first; i++) {
+ reordered.add(hostSpecs[i]);
+ }
+
+ return reordered.iterator();
+ }
+
+}
\ No newline at end of file
diff --git a/org/postgresql/hostchooser/LoadBalanceHostChooser.java b/org/postgresql/hostchooser/LoadBalanceHostChooser.java
new file mode 100644
index 0000000..1586e54
--- /dev/null
+++ b/org/postgresql/hostchooser/LoadBalanceHostChooser.java
@@ -0,0 +1,116 @@
+package org.postgresql.hostchooser;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.Properties;
+
+import org.postgresql.util.*;
+
+/*
+ * Pick up one from known good hosts randomly first and then try others
+ *
+ * @author Chen Huajun (chenhj@cn.fujitsu.com)
+ */
+public class LoadBalanceHostChooser extends HostChooserWithStatusReport
+{
+ private final HostSpec[] hostSpecs;
+ private String targetServerType;
+ private int failedHostCheckPeriod;
+ private static long lastfailedHostCheckTime = new Date().getTime();
+
+ public LoadBalanceHostChooser(HostSpec[] hostSpecs,Properties info) {
+ this.hostSpecs = hostSpecs;
+ targetServerType = info.getProperty("targetServerType", "any").toLowerCase();
+ failedHostCheckPeriod = Integer.parseInt(info.getProperty("failedHostCheckPeriod", "600"))*1000;
+ }
+
+ public Iterator<HostSpec> iterator() {
+ long now = new Date().getTime();
+ if(failedHostCheckPeriod >0 && now > lastfailedHostCheckTime + failedHostCheckPeriod)
+ {
+ int connectFailCount = 0;
+ Iterator<String> iter = hostStatusMap.keySet().iterator();
+ while(iter.hasNext()){
+ String key = iter.next();
+ if(hostStatusMap.get(key) == HostStatus.ConnectFail){
+ connectFailCount++;
+ }
+ }
+
+ if(connectFailCount > 0)
+ {
+ synchronized(HostChooserWithStatusReport.class){
+ if(now > lastfailedHostCheckTime + failedHostCheckPeriod)
+ {
+ iter = hostStatusMap.keySet().iterator();
+ while(iter.hasNext()){
+ String key = iter.next();
+ if(hostStatusMap.get(key) == HostStatus.ConnectFail){
+ reportHostStatus(key, null);
+ }
+ }
+ lastfailedHostCheckTime = now;
+ }
+ }
+ }
+ }
+
+ ArrayList<HostSpec> reordered = new ArrayList<HostSpec>(hostSpecs.length);
+ ArrayList<HostSpec> rest = new ArrayList<HostSpec>(hostSpecs.length);
+ for (int i = 0; i < hostSpecs.length; i++) {
+ rest.add(hostSpecs[i]);
+ HostStatus hostStatus = hostStatusMap.get(hostSpecs[i].toString());
+ if(hostStatus != null){
+ if(targetServerType.equals("any") && hostStatus != HostStatus.ConnectFail){
+ reordered.add(hostSpecs[i]);
+ rest.remove(rest.size()-1);
+ continue;
+ }
+
+ if(targetServerType.equals("master") && hostStatus == HostStatus.Master){
+ reordered.add(hostSpecs[i]);
+ rest.remove(rest.size()-1);
+ continue;
+ }
+
+ if((targetServerType.equals("slave") || targetServerType.equals("slavefirst")) &&
+ hostStatus == HostStatus.Slave){
+ reordered.add(hostSpecs[i]);
+ rest.remove(rest.size()-1);
+ continue;
+ }
+ }else{
+ reordered.add(hostSpecs[i]);
+ rest.remove(rest.size()-1);
+ continue;
+ }
+ }
+
+ if(reordered.size() == 0 && targetServerType.equals("slavefirst")){
+ for (int i = 0; i < hostSpecs.length; i++) {
+ HostStatus hostStatus = hostStatusMap.get(hostSpecs[i].toString());
+ if(hostStatus != null){
+ if(hostStatus != HostStatus.ConnectFail){
+ reordered.add(hostSpecs[i]);
+ rest.remove(hostSpecs[i]);
+ }
+ }
+ }
+ }
+
+ if (reordered.size() > 0) {
+ int first = (int)(Math.random() * reordered.size());
+ HostSpec tmpHostSpec=reordered.get(0);
+ reordered.set(0, reordered.get(first));
+ reordered.set(first,tmpHostSpec);
+ }
+
+ for (int i = 0; i < rest.size(); i++) {
+ reordered.add(rest.get(i));
+ }
+
+ return reordered.iterator();
+ }
+
+}
\ No newline at end of file
diff --git a/org/postgresql/hostchooser/SingleHostChooser.java b/org/postgresql/hostchooser/SingleHostChooser.java
new file mode 100644
index 0000000..08635b8
--- /dev/null
+++ b/org/postgresql/hostchooser/SingleHostChooser.java
@@ -0,0 +1,21 @@
+package org.postgresql.hostchooser;
+
+import java.util.Collections;
+import java.util.Iterator;
+
+import org.postgresql.util.*;
+
+public class SingleHostChooser implements HostChooser {
+ private final HostSpec hostSpec;
+
+ public SingleHostChooser(HostSpec hostSpec) {
+ this.hostSpec = hostSpec;
+ }
+
+ public Iterator<HostSpec> iterator() {
+ return Collections.singletonList(hostSpec).iterator();
+ }
+
+ public void reportHostStatus(HostSpec hostSpec, HostStatus hostStatus) {
+ }
+}
\ No newline at end of file=
MutiHostsConnectionTest.java (text/java, 10.6K) download
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.postgresql.ds.PGConnectionPoolDataSource;
import junit.framework.Assert;
//master 127.0.0.1:5432
//slave 127.0.0.1:5433
public class MutiHostsConnectionTest {
public static String getServerInfo(Connection con) throws SQLException{
ResultSet rs = con.createStatement().executeQuery("select inet_server_addr(),inet_server_port()");
rs.next();
String hostspec = rs.getString(1)+":"+rs.getString(2);
return hostspec;
}
public static void testFailOver() throws SQLException{
System.out.println("");
System.out.println("");
System.out.println("test()");
Connection con;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
String url = "jdbc:postgresql://127.0.0.1:5433,notahost:0001/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertEquals("127.0.0.1:5433", getServerInfo(con));
con.close();
url = "jdbc:postgresql://notahost:0002,127.0.0.1:5433/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertEquals("127.0.0.1:5433", getServerInfo(con));
con.close();
url = "jdbc:postgresql://127.0.0.1:5432,127.0.0.1:5433/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
//test targetServerType=Any
props.setProperty("targetServerType", "Any");
url = "jdbc:postgresql://127.0.0.1:5432,127.0.0.1:5433/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
//test targetServerType=Master
props.setProperty("targetServerType", "Master");
url = "jdbc:postgresql://127.0.0.1:5432,127.0.0.1:5433/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertTrue(isMaster(con));
con.close();
//test targetServerType=Slave
props.setProperty("targetServerType", "Slave");
url = "jdbc:postgresql://127.0.0.1:5433,127.0.0.1:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertFalse(isMaster(con));
con.close();
//test targetServerType=SlaveFirst
props.setProperty("targetServerType", "SlaveFirst");
url = "jdbc:postgresql://127.0.0.1:5433,127.0.0.1:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertFalse(isMaster(con));
con.close();
props.setProperty("targetServerType", "SlaveFirst");
url = "jdbc:postgresql://notahost:0001,127.0.0.1:5433/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertEquals("127.0.0.1:5433", getServerInfo(con));
con.close();
props.setProperty("targetServerType", "SlaveFirst");
url = "jdbc:postgresql://notahost:0001,127.0.0.1:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertEquals("127.0.0.1:5432", getServerInfo(con));
con.close();
}
public static void testLoadBalance() throws SQLException{
System.out.println("");
System.out.println("");
System.out.println("testLoadBalance()");
Connection con;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
props.setProperty("enableLoadBalance", "true");
String url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001,127.0.0.1:5432,localhost:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
//test targetServerType=Any
props.setProperty("targetServerType", "Any");
url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001,127.0.0.1:5432,localhost:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
//test targetServerType=Master
props.setProperty("targetServerType", "Master");
url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001,127.0.0.1:5432,localhost:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertTrue(isMaster(con));
con.close();
//test targetServerType=Slave
props.setProperty("targetServerType", "Slave");
url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001,127.0.0.1:5432,localhost:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertFalse(isMaster(con));
con.close();
//test targetServerType=Slave
props.setProperty("targetServerType", "Slave");
url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001,localhost:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertFalse(isMaster(con));
con.close();
//test targetServerType=SlaveFirst
props.setProperty("targetServerType", "SlaveFirst");
url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001,127.0.0.1:5433,localhost:5432/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertFalse(isMaster(con));
con.close();
props.setProperty("targetServerType", "SlaveFirst");
url = "jdbc:postgresql://127.0.0.1:5433,localhost:5433,notahost:0001/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertEquals("127.0.0.1:5433", getServerInfo(con));
con.close();
props.setProperty("targetServerType", "SlaveFirst");
url = "jdbc:postgresql://127.0.0.1:5432,localhost:5432,notahost:0001/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+url);
Assert.assertEquals("127.0.0.1:5432", getServerInfo(con));
con.close();
}
public static void testLoadBalanceWithFailedReCheck() throws SQLException, IOException{
System.out.println("");
System.out.println("");
System.out.println("testLoadBalanceWithFailedReCheck()");
Connection con;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
props.setProperty("enableLoadBalance", "true");
props.setProperty("failedHostCheckPeriod", "3");
props.setProperty("targetServerType", "SlaveFirst");
System.out.println("Stop the slave and press enter");
System.in.read();
System.in.read();
String url = "jdbc:postgresql://127.0.0.1:5432,127.0.0.1:5433/postgres"+protocolVersion;
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
Assert.assertTrue(isMaster(con));
con.close();
System.out.println("Start the slave and press enter after 5 seconds");
System.in.read();
System.in.read();
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
con.close();
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
Assert.assertFalse(isMaster(con));
con.close();
}
public static void testURL() throws SQLException{
System.out.println("");
System.out.println("");
System.out.println("testURL()");
Connection con;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", password);
String url = "jdbc:postgresql://127.0.0.1:5432,127.0.0.1:5433/postgres?targetServerType=master";
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
Assert.assertTrue(isMaster(con));
con.close();
url = "jdbc:postgresql://127.0.0.1:5432,127.0.0.1:5433/postgres?targetServerType=slave";
con = DriverManager.getConnection(url,props);
System.out.println("Connect OK:"+getServerInfo(con)+":"+url);
Assert.assertFalse(isMaster(con));
con.close();
}
public static boolean isMaster(Connection con) throws SQLException{
ResultSet rs = con.createStatement().executeQuery("show transaction_read_only");
rs.next();
return "off".equalsIgnoreCase(rs.getString(1));
}
public static String protocolVersion = "";
public static String user = "chj";
public static String password = "postgres";
/**
* @param args
*/
public static void main(String[] args) {
try {
Class.forName("org.postgresql.Driver");
protocolVersion = "?protocolVersion=3";
testFailOver();
testLoadBalance();
testURL();
//testLoadBalanceWithFailedReCheck();
System.out.println("OK");
} catch (Exception e) {
e.printStackTrace();
}
}
}
^ permalink raw reply [nested|flat] 13+ messages in thread
* Re: performance problem of Failover Datasource?
@ 2012-12-24 20:10 Scott Harrington <scotth01@sns-usa.com>
parent: Chen Huajun <chenhj@cn.fujitsu.com>
0 siblings, 1 reply; 13+ messages in thread
From: Scott Harrington @ 2012-12-24 20:10 UTC (permalink / raw)
To: pgsql-jdbc
Hmm, there's some neat stuff in there, slave-only, slavefirst, etc.
But could you (and perhaps Mikko Tiihonen who originally proposed the
"Simple connection failover support") remind the rest of us why we want
this complexity inside the pgjdbc driver, rather than in a more robust and
featureful layer like pgpool-II?
At first glance, there are a couple of issues:
1. Double-Checked Locking in reportHostStatus, which is bad form
2. Synchronized code in a subclass that locks the base class
3. No need for 'volatile' if you're also using 'synchronized'
Taking a step back, it seems you have implemented a DNS-like static
(JVM-global) helper which performs lazy-caching of information about
servers. I would argue PGJDBC itself should only do simple single-host
connections, but perhaps provide a well-documented HostChooser interface
and a JVM-global (static) method such as Driver.setHostChooser(), similar
to Driver.setLogLevel(), so that applicaitons that need to override the
default "DNS lookups" (or "host choosing") may do so.
Applications that want the load balancing would use something like
"host=myvirtualpool" which would would obviously fail unless the you've
installed some sort of LoadBalanceHostChooser, which knows about all the
"realservers" that comprise the "myvirtualpool" and their
master/slave/OK/dead status. (Starts to sound more and more like pgpool-II
or other projects that already exist for this).
Side benefit is your LoadBalanceHostChooser could be designed to do
"eager" connection probing on worker threads so that when an application
thread needs a PGJDBC connection, you would avoid any of the slow
connection / dead server issues you were originally trying to solve.
On Mon, 24 Dec 2012, Chen Huajun wrote:
> Hi
>
> I have made a new patch(with my test). Please give a look.
> It support the following features
> 1) performance improve for fail over by avoiding dead hosts.
> 2) simple load balance by picking up the first host from multiple valid hosts
> randomly.
> 3) ability of choosing master or slave to connect to.
>
> And in the patch, three connection parameters were added.
>
> targetServerType = String
> Specifies what kind of server to connect.The value should be one of the
> following:
> any
> master
> slave
> slavefirst (Try connecting to the slaves first.If failed try the master)
> The default is 'any'.
>
> enableLoadBalance = boolean
> Enable or disable load balance when multiple hosts were specified;If load
> balance is enabled,specified multiple hosts will be picked up randomly.
> The default is false.
>
> failedHostCheckPeriod = int
> Specifies period(seconds) to check whether the failed hosts had been
> repaired, when load balance is enabled; 0 means never check.
> The default is 600 seconds.
>
>
> (2012/12/18 8:05), Chen Huajun wrote:
>>
>> Thanks for you advise.
>> I will try to made a new patch and add load balance supporting.
>>
>>
>
> --
> Best Regards,
> Chen Huajun
>
>
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
^ permalink raw reply [nested|flat] 13+ messages in thread
* Re: performance problem of Failover Datasource?
@ 2012-12-25 13:45 Chen Huajun <chenhj@cn.fujitsu.com>
parent: Scott Harrington <scotth01@sns-usa.com>
0 siblings, 1 reply; 13+ messages in thread
From: Chen Huajun @ 2012-12-25 13:45 UTC (permalink / raw)
To: Scott Harrington <scotth01@sns-usa.com>; +Cc: pgsql-jdbc
> But could you (and perhaps Mikko Tiihonen who originally proposed the "Simple connection failover support") remind the rest of us why we want this complexity inside the pgjdbc driver, rather than in a
> more robust and featureful layer like pgpool-II?
I saw some mails discussed about this subject, but I don't know all.
I think the performance and simple is the reason.Is it right?
> Taking a step back, it seems you have implemented a DNS-like static (JVM-global) helper which performs lazy-caching of information about servers. I would argue PGJDBC itself should only do simple
> single-host connections, but perhaps provide a well-documented HostChooser interface and a JVM-global (static) method such as Driver.setHostChooser(), similar to Driver.setLogLevel(), so that
> applicaitons that need to override the default "DNS lookups" (or "host choosing") may do so.
I think the problem is if some simple HostChoosers are useful.
If yes and they are not so complex for a jdbc drvier,why not providing them.
By the way,if HostChooser implement choosing is needed,a JVM-global property(such as -Dxx.xx.HostChooser=XXXXHostChooser)
or a connection parameter may be more suitable,because they can avoid modifying applicaiton's source while change HostChooser implement.
> Applications that want the load balancing would use something like "host=myvirtualpool" which would would obviously fail unless the you've installed some sort of LoadBalanceHostChooser, which knows
> about all the "realservers" that comprise the "myvirtualpool" and their master/slave/OK/dead status. (Starts to sound more and more like pgpool-II or other projects that already exist for this).
Really I know some products just do as "host=myvirtualpool".
And sometime the form is more convenient and easy to customizing,
the shortcoming may be more complex just as you said.
Now ,Could you explain the the detail of following issues?
> At first glance, there are a couple of issues:
>
> 1. Double-Checked Locking in reportHostStatus, which is bad form
I knows a problem of Double-Checked Locking,while used in singleton pattern as following.
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
because JVM would run "instance = new Singleton(); " as that :
mem = allocate();
instance = mem;
ctorSingleton(instance);
Do you think my code has the same problem or just it looks ugly?
> 2. Synchronized code in a subclass that locks the base class
Synchronized code is for hostStatusCache which shared by all subclass,
so locks the base class.Is there any problems?
> 3. No need for 'volatile' if you're also using 'synchronized'
'synchronized' is only used for write,'volatile' is for read.
It's for performance and is a bit complex.(It may be a excessive design)
I worry about JVM will optimize the following code
HashMap<String,HostStatus> newHostStatusMap = (HashMap<String, HostStatus>) hostStatusCache.clone();
newHostStatusMap.put(hostSpecKey, hostStatus);
hostStatusCache=newHostStatusMap;
as:
hostStatusCache=(HashMap<String, HostStatus>) hostStatusCache.clone();
hostStatusCache.put(hostSpecKey, hostStatus);
do you know if it will happen?
(2012/12/25 4:10), Scott Harrington wrote:
> Hmm, there's some neat stuff in there, slave-only, slavefirst, etc.
>
> But could you (and perhaps Mikko Tiihonen who originally proposed the "Simple connection failover support") remind the rest of us why we want this complexity inside the pgjdbc driver, rather than in a
> more robust and featureful layer like pgpool-II?
>
> At first glance, there are a couple of issues:
>
> 1. Double-Checked Locking in reportHostStatus, which is bad form
>
> 2. Synchronized code in a subclass that locks the base class
>
> 3. No need for 'volatile' if you're also using 'synchronized'
>
> Taking a step back, it seems you have implemented a DNS-like static (JVM-global) helper which performs lazy-caching of information about servers. I would argue PGJDBC itself should only do simple
> single-host connections, but perhaps provide a well-documented HostChooser interface and a JVM-global (static) method such as Driver.setHostChooser(), similar to Driver.setLogLevel(), so that
> applicaitons that need to override the default "DNS lookups" (or "host choosing") may do so.
>
> Applications that want the load balancing would use something like "host=myvirtualpool" which would would obviously fail unless the you've installed some sort of LoadBalanceHostChooser, which knows
> about all the "realservers" that comprise the "myvirtualpool" and their master/slave/OK/dead status. (Starts to sound more and more like pgpool-II or other projects that already exist for this).
>
> Side benefit is your LoadBalanceHostChooser could be designed to do "eager" connection probing on worker threads so that when an application thread needs a PGJDBC connection, you would avoid any of
> the slow connection / dead server issues you were originally trying to solve.
>
>
> On Mon, 24 Dec 2012, Chen Huajun wrote:
>
>> Hi
>>
>> I have made a new patch(with my test). Please give a look.
>> It support the following features
>> 1) performance improve for fail over by avoiding dead hosts.
>> 2) simple load balance by picking up the first host from multiple valid hosts randomly.
>> 3) ability of choosing master or slave to connect to.
>>
>> And in the patch, three connection parameters were added.
>>
>> targetServerType = String
>> Specifies what kind of server to connect.The value should be one of the following:
>> any
>> master
>> slave
>> slavefirst (Try connecting to the slaves first.If failed try the master)
>> The default is 'any'.
>>
>> enableLoadBalance = boolean
>> Enable or disable load balance when multiple hosts were specified;If load balance is enabled,specified multiple hosts will be picked up randomly.
>> The default is false.
>>
>> failedHostCheckPeriod = int
>> Specifies period(seconds) to check whether the failed hosts had been repaired, when load balance is enabled; 0 means never check.
>> The default is 600 seconds.
>>
>>
>> (2012/12/18 8:05), Chen Huajun wrote:
>>>
>>> Thanks for you advise.
>>> I will try to made a new patch and add load balance supporting.
>>>
>>>
>>
>> --
>> Best Regards,
>> Chen Huajun
>>
>>
>
>
--
Best Regards,
Chen Huajun
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
^ permalink raw reply [nested|flat] 13+ messages in thread
* Re: performance problem of Failover Datasource?
@ 2012-12-26 11:17 Florent Guillaume <fg@nuxeo.com>
parent: Chen Huajun <chenhj@cn.fujitsu.com>
0 siblings, 1 reply; 13+ messages in thread
From: Florent Guillaume @ 2012-12-26 11:17 UTC (permalink / raw)
To: Chen Huajun <chenhj@cn.fujitsu.com>; +Cc: Scott Harrington <scotth01@sns-usa.com>; pgsql-jdbc
On Tue, Dec 25, 2012 at 2:45 PM, Chen Huajun <chenhj@cn.fujitsu.com> wrote:
> Now ,Could you explain the the detail of following issues?
>> At first glance, there are a couple of issues:
>>
>> 1. Double-Checked Locking in reportHostStatus, which is bad form
>
> I knows a problem of Double-Checked Locking,while used in singleton pattern
> as following.
>
> public static Singleton getInstance() {
> if (instance == null) {
> synchronized (Singleton.class) {
> if (instance == null) {
> instance = new Singleton();
> }
> }
> }
> return instance;
> }
>
> because JVM would run "instance = new Singleton(); " as that :
>
> mem = allocate();
> instance = mem;
> ctorSingleton(instance);
>
> Do you think my code has the same problem or just it looks ugly?
Double-checked locking generally is incorrect, and does not work. It
ONLY works if you're double-checking a volatile variable and using
Java >= 5.
Please read http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
>> 3. No need for 'volatile' if you're also using 'synchronized'
>
> 'synchronized' is only used for write,'volatile' is for read.
This sentence shows you're confused about synchronization and
multi-threading in Java.
> It's for performance and is a bit complex.(It may be a excessive design)
> I worry about JVM will optimize the following code
>
> HashMap<String,HostStatus> newHostStatusMap = (HashMap<String,
> HostStatus>) hostStatusCache.clone();
> newHostStatusMap.put(hostSpecKey, hostStatus);
> hostStatusCache=newHostStatusMap;
> as:
> hostStatusCache=(HashMap<String, HostStatus>) hostStatusCache.clone();
> hostStatusCache.put(hostSpecKey, hostStatus);
>
> do you know if it will happen?
Of course it can. The JVM is free to reorder a lot of things while
respecting the Java Memory Model.
All this means you shouldn't try to play games with the JVM, just use
a basic lock or synchronization primitive where you need it.
Florent
--
Florent Guillaume, Director of R&D, Nuxeo
Open Source, Java EE based, Enterprise Content Management (ECM)
http://www.nuxeo.com http://www.nuxeo.org +33 1 40 33 79 87
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
^ permalink raw reply [nested|flat] 13+ messages in thread
* Re: performance problem of Failover Datasource?
@ 2012-12-26 11:45 Chen Huajun <chenhj@cn.fujitsu.com>
parent: Florent Guillaume <fg@nuxeo.com>
0 siblings, 0 replies; 13+ messages in thread
From: Chen Huajun @ 2012-12-26 11:45 UTC (permalink / raw)
To: Florent Guillaume <fg@nuxeo.com>; +Cc: Scott Harrington <scotth01@sns-usa.com>; pgsql-jdbc
I got it, thanks!
(2012/12/26 19:17), Florent Guillaume wrote:
> On Tue, Dec 25, 2012 at 2:45 PM, Chen Huajun<chenhj@cn.fujitsu.com> wrote:
>> Now ,Could you explain the the detail of following issues?
>>> At first glance, there are a couple of issues:
>>>
>>> 1. Double-Checked Locking in reportHostStatus, which is bad form
>>
>> I knows a problem of Double-Checked Locking,while used in singleton pattern
>> as following.
>>
>> public static Singleton getInstance() {
>> if (instance == null) {
>> synchronized (Singleton.class) {
>> if (instance == null) {
>> instance = new Singleton();
>> }
>> }
>> }
>> return instance;
>> }
>>
>> because JVM would run "instance = new Singleton(); " as that :
>>
>> mem = allocate();
>> instance = mem;
>> ctorSingleton(instance);
>>
>> Do you think my code has the same problem or just it looks ugly?
>
> Double-checked locking generally is incorrect, and does not work. It
> ONLY works if you're double-checking a volatile variable and using
> Java>= 5.
> Please read http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html
>
>
>>> 3. No need for 'volatile' if you're also using 'synchronized'
>>
>> 'synchronized' is only used for write,'volatile' is for read.
>
> This sentence shows you're confused about synchronization and
> multi-threading in Java.
>
>> It's for performance and is a bit complex.(It may be a excessive design)
>> I worry about JVM will optimize the following code
>>
>> HashMap<String,HostStatus> newHostStatusMap = (HashMap<String,
>> HostStatus>) hostStatusCache.clone();
>> newHostStatusMap.put(hostSpecKey, hostStatus);
>> hostStatusCache=newHostStatusMap;
>> as:
>> hostStatusCache=(HashMap<String, HostStatus>) hostStatusCache.clone();
>> hostStatusCache.put(hostSpecKey, hostStatus);
>>
>> do you know if it will happen?
>
> Of course it can. The JVM is free to reorder a lot of things while
> respecting the Java Memory Model.
>
> All this means you shouldn't try to play games with the JVM, just use
> a basic lock or synchronization primitive where you need it.
>
> Florent
>
> --
> Florent Guillaume, Director of R&D, Nuxeo
> Open Source, Java EE based, Enterprise Content Management (ECM)
> http://www.nuxeo.com http://www.nuxeo.org +33 1 40 33 79 87
>
>
--
Best Regards,
Chen Huajun
--
Sent via pgsql-jdbc mailing list (pgsql-jdbc@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-jdbc
^ permalink raw reply [nested|flat] 13+ messages in thread
end of thread, other threads:[~2012-12-26 11:45 UTC | newest]
Thread overview: 13+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2012-12-13 10:42 Re: performance problem of Failover Datasource? Chen Huajun <chenhj@cn.fujitsu.com>
2012-12-13 21:01 ` Dave Cramer <pg@fastcrypt.com>
2012-12-14 02:57 ` Chen Huajun <chenhj@cn.fujitsu.com>
2012-12-14 13:29 ` Chen Huajun <chenhj@cn.fujitsu.com>
2012-12-15 07:10 ` Chen Huajun <chenhj@cn.fujitsu.com>
2012-12-15 16:19 ` Scott Harrington <scotth01@sns-usa.com>
2012-12-18 00:05 ` Chen Huajun <chenhj@cn.fujitsu.com>
2012-12-24 10:26 ` Chen Huajun <chenhj@cn.fujitsu.com>
2012-12-24 20:10 ` Scott Harrington <scotth01@sns-usa.com>
2012-12-25 13:45 ` Chen Huajun <chenhj@cn.fujitsu.com>
2012-12-26 11:17 ` Florent Guillaume <fg@nuxeo.com>
2012-12-26 11:45 ` Chen Huajun <chenhj@cn.fujitsu.com>
2012-12-18 00:29 ` Craig Ringer <craig@2ndquadrant.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox