提交 7649a8be 编写于 作者: 武汉红喜's avatar 武汉红喜

code optimise

上级 b22666cb
......@@ -60,12 +60,6 @@
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common;
import java.util.concurrent.TimeUnit;
......@@ -34,8 +17,9 @@ public class CountDownLatch2 {
* @throws IllegalArgumentException if {@code count} is negative
*/
public CountDownLatch2(int count) {
if (count < 0)
if (count < 0) {
throw new IllegalArgumentException("count < 0");
}
this.sync = new Sync(count);
}
......@@ -150,6 +134,7 @@ public class CountDownLatch2 {
*
* @return a string identifying this latch, as well as its state
*/
@Override
public String toString() {
return super.toString() + "[Count = " + sync.getCount() + "]";
}
......@@ -172,19 +157,23 @@ public class CountDownLatch2 {
return getState();
}
@Override
protected int tryAcquireShared(int acquires) {
return (getState() == 0) ? 1 : -1;
}
@Override
protected boolean tryReleaseShared(int releases) {
// Decrement count; signal when transition to zero
for (; ; ) {
int c = getState();
if (c == 0)
if (c == 0) {
return false;
}
int nextc = c - 1;
if (compareAndSetState(c, nextc))
if (compareAndSetState(c, nextc)) {
return nextc == 0;
}
}
}
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
public class ThreadFactoryImpl implements ThreadFactory {
private final AtomicLong threadIndex = new AtomicLong(0);
private final String threadNamePrefix;
private final boolean daemon;
public ThreadFactoryImpl(final String threadNamePrefix) {
this(threadNamePrefix, false);
}
public ThreadFactoryImpl(final String threadNamePrefix, boolean daemon) {
this.threadNamePrefix = threadNamePrefix;
this.daemon = daemon;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, threadNamePrefix + this.threadIndex.incrementAndGet());
thread.setDaemon(daemon);
return thread;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common;
import lombok.extern.slf4j.Slf4j;
......@@ -177,14 +161,16 @@ public class UtilAll {
}
public static double getDiskPartitionSpaceUsedPercent(final String path) {
if (null == path || path.isEmpty())
if (null == path || path.isEmpty()) {
return -1;
}
try {
File file = new File(path);
if (!file.exists())
if (!file.exists()) {
return -1;
}
long totalSpace = file.getTotalSpace();
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.config;
import org.hongxi.whatsmars.common.util.StringUtils;
/**
* This is an abstraction specially customized for the sequence Dubbo retrieves properties.
*/
public abstract class AbstractPrefixConfiguration implements Configuration {
protected String id;
protected String prefix;
public AbstractPrefixConfiguration(String prefix, String id) {
super();
if (StringUtils.isNotEmpty(prefix) && !prefix.endsWith(".")) {
this.prefix = prefix + ".";
} else {
this.prefix = prefix;
}
this.id = id;
}
@Override
public Object getProperty(String key, Object defaultValue) {
Object value = null;
if (StringUtils.isNotEmpty(prefix) && StringUtils.isNotEmpty(id)) {
value = getInternalProperty(prefix + id + "." + key);
}
if (value == null && StringUtils.isNotEmpty(prefix)) {
value = getInternalProperty(prefix + key);
}
if (value == null) {
value = getInternalProperty(key);
}
return value != null ? value : defaultValue;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
*
*/
public class CompositeConfiguration implements Configuration {
private Logger logger = LoggerFactory.getLogger(CompositeConfiguration.class);
/**
* List holding all the configuration
*/
private List<Configuration> configList = new LinkedList<Configuration>();
public CompositeConfiguration() {
}
public CompositeConfiguration(Configuration... configurations) {
if (configurations != null && configurations.length > 0) {
Arrays.stream(configurations).filter(config -> !configList.contains(config)).forEach(configList::add);
}
}
public void addConfiguration(Configuration configuration) {
if (configList.contains(configuration)) {
return;
}
this.configList.add(configuration);
}
public void addConfigurationFirst(Configuration configuration) {
this.addConfiguration(0, configuration);
}
public void addConfiguration(int pos, Configuration configuration) {
this.configList.add(pos, configuration);
}
@Override
public Object getInternalProperty(String key) {
Configuration firstMatchingConfiguration = null;
for (Configuration config : configList) {
try {
if (config.containsKey(key)) {
firstMatchingConfiguration = config;
break;
}
} catch (Exception e) {
logger.error("Error when trying to get value for key " + key + " from " + config + ", will continue to try the next one.");
}
}
if (firstMatchingConfiguration != null) {
return firstMatchingConfiguration.getProperty(key);
} else {
return null;
}
}
@Override
public boolean containsKey(String key) {
return configList.stream().anyMatch(c -> c.containsKey(key));
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.config;
/**
* Configuration interface, to fetch the value for the specified key.
*/
public interface Configuration {
/**
* Get a string associated with the given configuration key.
*
* @param key The configuration key.
* @return The associated string.
*/
default String getString(String key) {
return convert(String.class, key, null);
}
/**
* Get a string associated with the given configuration key.
* If the key doesn't map to an existing object, the default value
* is returned.
*
* @param key The configuration key.
* @param defaultValue The default value.
* @return The associated string if key is found and has valid
* format, default value otherwise.
*/
default String getString(String key, String defaultValue) {
return convert(String.class, key, defaultValue);
}
/**
* Gets a property from the configuration. This is the most basic get
* method for retrieving values of properties. In a typical implementation
* of the {@code Configuration} interface the other get methods (that
* return specific data types) will internally make use of this method. On
* this level variable substitution is not yet performed. The returned
* object is an internal representation of the property value for the passed
* in key. It is owned by the {@code Configuration} object. So a caller
* should not modify this object. It cannot be guaranteed that this object
* will stay constant over time (i.e. further update operations on the
* configuration may change its internal state).
*
* @param key property to retrieve
* @return the value to which this configuration maps the specified key, or
* null if the configuration contains no mapping for this key.
*/
default Object getProperty(String key) {
return getProperty(key, null);
}
/**
* Gets a property from the configuration. The default value will return if the configuration doesn't contain
* the mapping for the specified key.
*
* @param key property to retrieve
* @param defaultValue default value
* @return the value to which this configuration maps the specified key, or default value if the configuration
* contains no mapping for this key.
*/
default Object getProperty(String key, Object defaultValue) {
Object value = getInternalProperty(key);
return value != null ? value : defaultValue;
}
Object getInternalProperty(String key);
/**
* Check if the configuration contains the specified key.
*
* @param key the key whose presence in this configuration is to be tested
* @return {@code true} if the configuration contains a value for this
* key, {@code false} otherwise
*/
default boolean containsKey(String key) {
return getProperty(key) != null;
}
default <T> T convert(Class<T> cls, String key, T defaultValue) {
// we only process String properties for now
String value = (String) getProperty(key);
if (value == null) {
return defaultValue;
}
Object obj = value;
if (cls.isInstance(value)) {
return cls.cast(value);
}
if (String.class.equals(cls)) {
return cls.cast(value);
}
if (Boolean.class.equals(cls) || Boolean.TYPE.equals(cls)) {
obj = Boolean.valueOf(value);
} else if (Number.class.isAssignableFrom(cls) || cls.isPrimitive()) {
if (Integer.class.equals(cls) || Integer.TYPE.equals(cls)) {
obj = Integer.valueOf(value);
} else if (Long.class.equals(cls) || Long.TYPE.equals(cls)) {
obj = Long.valueOf(value);
} else if (Byte.class.equals(cls) || Byte.TYPE.equals(cls)) {
obj = Byte.valueOf(value);
} else if (Short.class.equals(cls) || Short.TYPE.equals(cls)) {
obj = Short.valueOf(value);
} else if (Float.class.equals(cls) || Float.TYPE.equals(cls)) {
obj = Float.valueOf(value);
} else if (Double.class.equals(cls) || Double.TYPE.equals(cls)) {
obj = Double.valueOf(value);
}
} else if (cls.isEnum()) {
obj = Enum.valueOf(cls.asSubclass(Enum.class), value);
}
return cls.cast(obj);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.config;
import org.hongxi.whatsmars.common.Constants;
/**
* Utilities for manipulating configurations from different sources
*/
public class ConfigurationUtils {
// FIXME
@SuppressWarnings("deprecation")
public static int getServerShutdownTimeout() {
int timeout = Constants.DEFAULT_SERVER_SHUTDOWN_TIMEOUT;
Configuration configuration = Environment.getInstance().getConfiguration();
String value = configuration.getString(Constants.SHUTDOWN_WAIT_KEY);
if (value != null && value.length() > 0) {
try {
timeout = Integer.parseInt(value);
} catch (Exception e) {
// ignore
}
} else {
value = configuration.getString(Constants.SHUTDOWN_WAIT_SECONDS_KEY);
if (value != null && value.length() > 0) {
try {
timeout = Integer.parseInt(value) * 1000;
} catch (Exception e) {
// ignore
}
}
}
return timeout;
}
public static String getProperty(String property) {
return getProperty(property, null);
}
public static String getProperty(String property, String defaultValue) {
return Environment.getInstance().getConfiguration().getString(property, defaultValue);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.config;
import org.hongxi.whatsmars.common.Constants;
import org.hongxi.whatsmars.common.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* TODO load as SPI will be better?
*/
public class Environment {
private static final Environment INSTANCE = new Environment();
private Map<String, PropertiesConfiguration> propertiesConfigs = new ConcurrentHashMap<>();
private Map<String, SystemConfiguration> systemConfigs = new ConcurrentHashMap<>();
private Map<String, EnvironmentConfiguration> environmentConfigs = new ConcurrentHashMap<>();
private Map<String, InmemoryConfiguration> externalConfigs = new ConcurrentHashMap<>();
private Map<String, InmemoryConfiguration> appExternalConfigs = new ConcurrentHashMap<>();
private Map<String, String> externalConfigurationMap = new HashMap<>();
private Map<String, String> appExternalConfigurationMap = new HashMap<>();
private boolean configCenterFirst = true;
/**
* FIXME, this instance will always be a type of DynamicConfiguration, ConfigCenterConfig will load the instance at startup and assign it to here.
*/
private Configuration dynamicConfiguration;
public static Environment getInstance() {
return INSTANCE;
}
public PropertiesConfiguration getPropertiesConfig(String prefix, String id) {
return propertiesConfigs.computeIfAbsent(toKey(prefix, id), k -> new PropertiesConfiguration(prefix, id));
}
public SystemConfiguration getSystemConfig(String prefix, String id) {
return systemConfigs.computeIfAbsent(toKey(prefix, id), k -> new SystemConfiguration(prefix, id));
}
public InmemoryConfiguration getExternalConfig(String prefix, String id) {
return externalConfigs.computeIfAbsent(toKey(prefix, id), k -> {
InmemoryConfiguration configuration = new InmemoryConfiguration(prefix, id);
configuration.setProperties(externalConfigurationMap);
return configuration;
});
}
public InmemoryConfiguration getAppExternalConfig(String prefix, String id) {
return appExternalConfigs.computeIfAbsent(toKey(prefix, id), k -> {
InmemoryConfiguration configuration = new InmemoryConfiguration(prefix, id);
configuration.setProperties(appExternalConfigurationMap);
return configuration;
});
}
public EnvironmentConfiguration getEnvironmentConfig(String prefix, String id) {
return environmentConfigs.computeIfAbsent(toKey(prefix, id), k -> new EnvironmentConfiguration(prefix, id));
}
public void setExternalConfigMap(Map<String, String> externalConfiguration) {
this.externalConfigurationMap = externalConfiguration;
}
public void setAppExternalConfigMap(Map<String, String> appExternalConfiguration) {
this.appExternalConfigurationMap = appExternalConfiguration;
}
public Map<String, String> getExternalConfigurationMap() {
return externalConfigurationMap;
}
public Map<String, String> getAppExternalConfigurationMap() {
return appExternalConfigurationMap;
}
public void updateExternalConfigurationMap(Map<String, String> externalMap) {
this.externalConfigurationMap.putAll(externalMap);
}
public void updateAppExternalConfigurationMap(Map<String, String> externalMap) {
this.appExternalConfigurationMap.putAll(externalMap);
}
/**
* Create new instance for each call, since it will be called only at startup, I think there's no big deal of the potential cost.
* Otherwise, if use cache, we should make sure each Config has a unique id which is difficult to guarantee because is on the user's side,
* especially when it comes to ServiceConfig and ReferenceConfig.
*
* @param prefix
* @param id
* @return
*/
public CompositeConfiguration getConfiguration(String prefix, String id) {
CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
// Config center has the highest priority
compositeConfiguration.addConfiguration(this.getSystemConfig(prefix, id));
compositeConfiguration.addConfiguration(this.getAppExternalConfig(prefix, id));
compositeConfiguration.addConfiguration(this.getExternalConfig(prefix, id));
compositeConfiguration.addConfiguration(this.getPropertiesConfig(prefix, id));
return compositeConfiguration;
}
public Configuration getConfiguration() {
return getConfiguration(null, null);
}
private static String toKey(String prefix, String id) {
StringBuilder sb = new StringBuilder();
if (StringUtils.isNotEmpty(prefix)) {
sb.append(prefix);
}
if (StringUtils.isNotEmpty(id)) {
sb.append(id);
}
if (sb.length() > 0 && sb.charAt(sb.length() - 1) != '.') {
sb.append(".");
}
if (sb.length() > 0) {
return sb.toString();
}
return Constants.DUBBO;
}
public boolean isConfigCenterFirst() {
return configCenterFirst;
}
public void setConfigCenterFirst(boolean configCenterFirst) {
this.configCenterFirst = configCenterFirst;
}
public Optional<Configuration> getDynamicConfiguration() {
return Optional.ofNullable(dynamicConfiguration);
}
public void setDynamicConfiguration(Configuration dynamicConfiguration) {
this.dynamicConfiguration = dynamicConfiguration;
}
// For test
public void clearExternalConfigs() {
this.externalConfigs.clear();
}
// For test
public void clearAppExternalConfigs() {
this.appExternalConfigs.clear();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.config;
/**
* Configuration from system environment
*/
public class EnvironmentConfiguration extends AbstractPrefixConfiguration {
public EnvironmentConfiguration(String prefix, String id) {
super(prefix, id);
}
public EnvironmentConfiguration() {
this(null, null);
}
@Override
public Object getInternalProperty(String key) {
return System.getenv(key);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.config;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* In-memory configuration
*/
public class InmemoryConfiguration extends AbstractPrefixConfiguration {
// stores the configuration key-value pairs
private Map<String, String> store = new LinkedHashMap<>();
public InmemoryConfiguration(String prefix, String id) {
super(prefix, id);
}
public InmemoryConfiguration() {
this(null, null);
}
@Override
public Object getInternalProperty(String key) {
return store.get(key);
}
/**
* Add one property into the store, the previous value will be replaced if the key exists
*/
public void addProperty(String key, String value) {
store.put(key, value);
}
/**
* Add a set of properties into the store
*/
public void addProperties(Map<String, String> properties) {
if (properties != null) {
this.store.putAll(properties);
}
}
/**
* set store
*/
public void setProperties(Map<String, String> properties) {
if (properties != null) {
this.store = properties;
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.config;
import org.hongxi.whatsmars.common.util.ConfigUtils;
/**
* Configuration from system properties and dubbo.properties
*/
public class PropertiesConfiguration extends AbstractPrefixConfiguration {
public PropertiesConfiguration(String prefix, String id) {
super(prefix, id);
}
public PropertiesConfiguration() {
this(null, null);
}
@Override
public Object getInternalProperty(String key) {
return ConfigUtils.getProperty(key);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.config;
/**
* FIXME: is this really necessary? PropertiesConfiguration should have already covered this:
* @see PropertiesConfiguration
* @See ConfigUtils#getProperty(String)
*/
public class SystemConfiguration extends AbstractPrefixConfiguration {
public SystemConfiguration(String prefix, String id) {
super(prefix, id);
}
public SystemConfiguration() {
this(null, null);
}
@Override
public Object getInternalProperty(String key) {
return System.getProperty(key);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.consistenthash;
import java.security.MessageDigest;
......@@ -60,8 +44,9 @@ public class ConsistentHashRouter<T extends Node> {
* @param vNodeCount the number of virtual node of the physical node. Value should be greater than or equals to 0
*/
public void addNode(T pNode, int vNodeCount) {
if (vNodeCount < 0)
if (vNodeCount < 0) {
throw new IllegalArgumentException("illegal virtual node counts :" + vNodeCount);
}
int existingReplicas = getExistingReplicas(pNode);
for (int i = 0; i < vNodeCount; i++) {
VirtualNode<T> vNode = new VirtualNode<T>(pNode, i + existingReplicas);
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.consistenthash;
/**
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.consistenthash;
/**
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.consistenthash;
public class VirtualNode<T extends Node> implements Node {
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.io;
import java.io.IOException;
import java.io.InputStream;
/**
* Stream utils.
*/
public class StreamUtils {
private StreamUtils() {
}
public static InputStream limitedInputStream(final InputStream is, final int limit) throws IOException {
return new InputStream() {
private int mPosition = 0, mMark = 0, mLimit = Math.min(limit, is.available());
@Override
public int read() throws IOException {
if (mPosition < mLimit) {
mPosition++;
return is.read();
}
return -1;
}
@Override
public int read(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
}
if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
}
if (mPosition >= mLimit) {
return -1;
}
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
}
if (len <= 0) {
return 0;
}
is.read(b, off, len);
mPosition += len;
return len;
}
@Override
public long skip(long len) throws IOException {
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
}
if (len <= 0) {
return 0;
}
is.skip(len);
mPosition += len;
return len;
}
@Override
public int available() {
return mLimit - mPosition;
}
@Override
public boolean markSupported() {
return is.markSupported();
}
@Override
public void mark(int readlimit) {
is.mark(readlimit);
mMark = mPosition;
}
@Override
public void reset() throws IOException {
is.reset();
mPosition = mMark;
}
@Override
public void close() throws IOException {
is.close();
}
};
}
public static InputStream markSupportedInputStream(final InputStream is, final int markBufferSize) {
if (is.markSupported()) {
return is;
}
return new InputStream() {
byte[] mMarkBuffer;
boolean mInMarked = false;
boolean mInReset = false;
boolean mDry = false;
private int mPosition = 0;
private int mCount = 0;
@Override
public int read() throws IOException {
if (!mInMarked) {
return is.read();
} else {
if (mPosition < mCount) {
byte b = mMarkBuffer[mPosition++];
return b & 0xFF;
}
if (!mInReset) {
if (mDry) {
return -1;
}
if (null == mMarkBuffer) {
mMarkBuffer = new byte[markBufferSize];
}
if (mPosition >= markBufferSize) {
throw new IOException("Mark buffer is full!");
}
int read = is.read();
if (-1 == read) {
mDry = true;
return -1;
}
mMarkBuffer[mPosition++] = (byte) read;
mCount++;
return read;
} else {
// mark buffer is used, exit mark status!
mInMarked = false;
mInReset = false;
mPosition = 0;
mCount = 0;
return is.read();
}
}
}
/**
* NOTE: the <code>readlimit</code> argument for this class
* has no meaning.
*/
@Override
public synchronized void mark(int readlimit) {
mInMarked = true;
mInReset = false;
// mark buffer is not empty
int count = mCount - mPosition;
if (count > 0) {
System.arraycopy(mMarkBuffer, mPosition, mMarkBuffer, 0, count);
mCount = count;
mPosition = 0;
}
}
@Override
public synchronized void reset() throws IOException {
if (!mInMarked) {
throw new IOException("should mark before reset!");
}
mInReset = true;
mPosition = 0;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public int available() throws IOException {
int available = is.available();
if (mInMarked && mInReset) {
available += mCount - mPosition;
}
return available;
}
@Override
public void close() throws IOException {
is.close();
}
};
}
public static InputStream markSupportedInputStream(final InputStream is) {
return markSupportedInputStream(is, 1024);
}
public static void skipUnusedStream(InputStream is) throws IOException {
if (is.available() > 0) {
is.skip(is.available());
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.io;
import java.io.IOException;
import java.io.InputStream;
/**
* UnsafeByteArrayInputStream.
*/
public class UnsafeByteArrayInputStream extends InputStream {
protected byte mData[];
protected int mPosition, mLimit, mMark = 0;
public UnsafeByteArrayInputStream(byte buf[]) {
this(buf, 0, buf.length);
}
public UnsafeByteArrayInputStream(byte buf[], int offset) {
this(buf, offset, buf.length - offset);
}
public UnsafeByteArrayInputStream(byte buf[], int offset, int length) {
mData = buf;
mPosition = mMark = offset;
mLimit = Math.min(offset + length, buf.length);
}
@Override
public int read() {
return (mPosition < mLimit) ? (mData[mPosition++] & 0xff) : -1;
}
@Override
public int read(byte b[], int off, int len) {
if (b == null) {
throw new NullPointerException();
}
if (off < 0 || len < 0 || len > b.length - off) {
throw new IndexOutOfBoundsException();
}
if (mPosition >= mLimit) {
return -1;
}
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
}
if (len <= 0) {
return 0;
}
System.arraycopy(mData, mPosition, b, off, len);
mPosition += len;
return len;
}
@Override
public long skip(long len) {
if (mPosition + len > mLimit) {
len = mLimit - mPosition;
}
if (len <= 0) {
return 0;
}
mPosition += len;
return len;
}
@Override
public int available() {
return mLimit - mPosition;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void mark(int readAheadLimit) {
mMark = mPosition;
}
@Override
public void reset() {
mPosition = mMark;
}
@Override
public void close() throws IOException {
}
public int position() {
return mPosition;
}
public void position(int newPosition) {
mPosition = newPosition;
}
public int size() {
return mData == null ? 0 : mData.length;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.io;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
/**
* UnsafeByteArrayOutputStream.
*/
public class UnsafeByteArrayOutputStream extends OutputStream {
protected byte mBuffer[];
protected int mCount;
public UnsafeByteArrayOutputStream() {
this(32);
}
public UnsafeByteArrayOutputStream(int size) {
if (size < 0) {
throw new IllegalArgumentException("Negative initial size: " + size);
}
mBuffer = new byte[size];
}
@Override
public void write(int b) {
int newcount = mCount + 1;
if (newcount > mBuffer.length) {
mBuffer = Bytes.copyOf(mBuffer, Math.max(mBuffer.length << 1, newcount));
}
mBuffer[mCount] = (byte) b;
mCount = newcount;
}
@Override
public void write(byte b[], int off, int len) {
if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (len == 0) {
return;
}
int newcount = mCount + len;
if (newcount > mBuffer.length) {
mBuffer = Bytes.copyOf(mBuffer, Math.max(mBuffer.length << 1, newcount));
}
System.arraycopy(b, off, mBuffer, mCount, len);
mCount = newcount;
}
public int size() {
return mCount;
}
public void reset() {
mCount = 0;
}
public byte[] toByteArray() {
return Bytes.copyOf(mBuffer, mCount);
}
public ByteBuffer toByteBuffer() {
return ByteBuffer.wrap(mBuffer, 0, mCount);
}
public void writeTo(OutputStream out) throws IOException {
out.write(mBuffer, 0, mCount);
}
@Override
public String toString() {
return new String(mBuffer, 0, mCount);
}
public String toString(String charset) throws UnsupportedEncodingException {
return new String(mBuffer, 0, mCount, charset);
}
@Override
public void close() throws IOException {
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.io;
import java.io.IOException;
import java.io.Reader;
/**
* Thread-unsafe StringReader.
*/
public class UnsafeStringReader extends Reader {
private String mString;
private int mPosition, mLimit, mMark;
public UnsafeStringReader(String str) {
mString = str;
mLimit = str.length();
mPosition = mMark = 0;
}
@Override
public int read() throws IOException {
ensureOpen();
if (mPosition >= mLimit) {
return -1;
}
return mString.charAt(mPosition++);
}
@Override
public int read(char[] cs, int off, int len) throws IOException {
ensureOpen();
if ((off < 0) || (off > cs.length) || (len < 0) ||
((off + len) > cs.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (len == 0) {
return 0;
}
if (mPosition >= mLimit) {
return -1;
}
int n = Math.min(mLimit - mPosition, len);
mString.getChars(mPosition, mPosition + n, cs, off);
mPosition += n;
return n;
}
@Override
public long skip(long ns) throws IOException {
ensureOpen();
if (mPosition >= mLimit) {
return 0;
}
long n = Math.min(mLimit - mPosition, ns);
n = Math.max(-mPosition, n);
mPosition += n;
return n;
}
@Override
public boolean ready() throws IOException {
ensureOpen();
return true;
}
@Override
public boolean markSupported() {
return true;
}
@Override
public void mark(int readAheadLimit) throws IOException {
if (readAheadLimit < 0) {
throw new IllegalArgumentException("Read-ahead limit < 0");
}
ensureOpen();
mMark = mPosition;
}
@Override
public void reset() throws IOException {
ensureOpen();
mPosition = mMark;
}
@Override
public void close() throws IOException {
mString = null;
}
private void ensureOpen() throws IOException {
if (mString == null) {
throw new IOException("Stream closed");
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.io;
import java.io.IOException;
import java.io.Writer;
/**
* Thread-unsafe StringWriter.
*/
public class UnsafeStringWriter extends Writer {
private StringBuilder mBuffer;
public UnsafeStringWriter() {
lock = mBuffer = new StringBuilder();
}
public UnsafeStringWriter(int size) {
if (size < 0) {
throw new IllegalArgumentException("Negative buffer size");
}
lock = mBuffer = new StringBuilder();
}
@Override
public void write(int c) {
mBuffer.append((char) c);
}
@Override
public void write(char[] cs) throws IOException {
mBuffer.append(cs, 0, cs.length);
}
@Override
public void write(char[] cs, int off, int len) throws IOException {
if ((off < 0) || (off > cs.length) || (len < 0) ||
((off + len) > cs.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
}
if (len > 0) {
mBuffer.append(cs, off, len);
}
}
@Override
public void write(String str) {
mBuffer.append(str);
}
@Override
public void write(String str, int off, int len) {
mBuffer.append(str.substring(off, off + len));
}
@Override
public Writer append(CharSequence csq) {
if (csq == null) {
write("null");
} else {
write(csq.toString());
}
return this;
}
@Override
public Writer append(CharSequence csq, int start, int end) {
CharSequence cs = (csq == null ? "null" : csq);
write(cs.subSequence(start, end).toString());
return this;
}
@Override
public Writer append(char c) {
mBuffer.append(c);
return this;
}
@Override
public void close() {
}
@Override
public void flush() {
}
@Override
public String toString() {
return mBuffer.toString();
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.queue;
import java.util.Comparator;
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.queue;
import java.util.LinkedList;
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.threadlocal;
/**
......
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.hongxi.whatsmars.common.threadlocal;
import java.util.Collections;
......
/*
* Copyright 2014 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package org.hongxi.whatsmars.common.threadlocal;
import java.util.Arrays;
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hongxi.whatsmars.common.threadlocal;
import org.hongxi.whatsmars.common.util.NamedThreadFactory;
......
package org.hongxi.whatsmars.common.threadpool;
import org.hongxi.whatsmars.common.threadlocal.NamedInternalThreadFactory;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* EagerThreadPool
* When the core threads are all in busy,
* create new thread instead of putting task into blocking queue.
*/
public class EagerThreadPool {
public Executor getExecutor(String name, int cores, int nThreads, int queues, int alive) {
// init queue and executor
TaskQueue<Runnable> taskQueue = new TaskQueue<Runnable>(queues <= 0 ? 1 : queues);
EagerThreadPoolExecutor executor = new EagerThreadPoolExecutor(cores,
nThreads,
alive,
TimeUnit.MILLISECONDS,
taskQueue,
new NamedInternalThreadFactory(name, true),
new ThreadPoolExecutor.AbortPolicy());
taskQueue.setExecutor(executor);
return executor;
}
}
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册