I am working on a project in which I have two tables in a different database with different schemas. So that means I have two different connection parameters for those two tables to connect using JDBC-
Let's suppose below is the config.property file- in which table1.percentage
means 80%
of time table1
will be picked and 20%
of time table2
will be picked basis on the random number.
TABLES: table1 table2
#For Table1
table1.percentage: 80
#For Table2
table2.percentage: 20
Below method will read the above config.property
file and make a ReadTableConnectionInfo
object for each tables.
private static HashMap<String, ReadTableConnectionInfo> tableList = new HashMap<String, ReadTableConnectionInfo>();
private static void readPropertyFile() throws IOException {
prop.load(Read.class.getClassLoader().getResourceAsStream("config.properties"));
tableNames = Arrays.asList(prop.getProperty("TABLES").split(" "));
for (String arg : tableNames) {
ReadTableConnectionInfo ci = new ReadTableConnectionInfo();
double percentage = Double.parseDouble(prop.getProperty(arg + ".percentage"));
ci.setPercentage(percentage);
tableList.put(arg, ci);
}
}
Below is the ReadTableConnectionInfo
class that will hold all the table connection info
for a particular table.
public class ReadTableConnectionInfo {
public String percentage;
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
}
Now in my run method each thread has to generate random number and then decide which table I need to use depending on the percentage for each tables.
private static Random random = new SecureRandom();
@Override
public run() {
...
while ( < 60 minutes) {
double randomNumber = random.nextDouble() * 100.0;
ReadTableConnectionInfo tableInfo = selectRandomConnection(randomNumber);
// do query...
}
}
//Any problem with the below method?
private ReadTableConnectionInfo selectRandomConnection(double randomNumber) {
double limit = 0;
for (ReadTableConnectionInfo ci : tableLists.values()) {
limit += ci.getPercentage();
if (randomNumber < limit) {
return ci;
}
}
throw new IllegalStateException();
}
Problem Statement:-
Is there any problem in my selectRandomConnection
method? Because each thread is working for 60 minutes and in that 60 minutes every time it is only picking table1
.
What I am looking for is 80%
of time it should pick table1
and 20%
of time it should pick table2
.