- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试不使用锁而是使用多版本并发控制来解决多线程银行帐户问题*。工作正常有点慢。我如何加快速度?
(*)我有5个用户,每个用户以200开始-每个用户随机提取100,然后将100存入另一个用户拥有的另一个银行帐户。我预计到运行结束时,银行结余总计为1000。不应损失或创造任何金钱。这部分适用于下面的实现。
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
import java.util.function.Function;
public class ConcurrentWithdrawer {
private Map<String, Integer> database = new HashMap<>();
private int transactionCount = 0;
private final List<Transaction> transactions = Collections.synchronizedList(new ArrayList<>());
public static void main(String[] args) {
try {
new ConcurrentWithdrawer().run();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static int getRandomNumberInRange(int min, int max) {
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
public void run() throws ExecutionException, InterruptedException {
int startAmount = 200;
int numberAccounts = 5;
int totalMoney = 0;
for (int i = 0; i < numberAccounts; i++) {
database.put(String.format("account%d", i), startAmount);
totalMoney += startAmount;
}
ThreadPoolExecutor executor =
(ThreadPoolExecutor) Executors.newFixedThreadPool(5);
List<Future> futures = new ArrayList<Future>();
for (int i = 0; i < 5; i++) {
futures.add(executor.submit(new Callable<Integer>() {
@Override
public Integer call() {
for (int j = 0; j < 5; j++) {
Transaction transaction = beginTransaction(transactions, database);
transaction.read("fromBalance", "fromAccountName", (context) -> {
int fromAccount = getRandomNumberInRange(0, 4);
String fromAccountName = String.format("account%d", fromAccount);
return fromAccountName;
}).read("toBalance", "toAccountName", (context) -> {
int toAccount = getRandomNumberInRange(0, 4);
String toAccountName = String.format("account%d", toAccount);
while (toAccountName.equals(context.lookupName("fromAccountName"))) {
toAccount = getRandomNumberInRange(0, 4);
toAccountName = String.format("account%d", toAccount);
}
return toAccountName;
}).write("fromAccountName", (writeContext) -> {
int difference;
TransactionContext context = writeContext.context;
if (context.get("fromBalance") >= 100) {
difference = 100;
} else {
difference = 0;
}
context.write(writeContext.writeStep, "fromAccountName", context.get("fromBalance") - difference);
context.put("difference", difference);
}).write("toAccountName", (writeContext) -> {
TransactionContext context = writeContext.context;
context.write(writeContext.writeStep, "toAccountName", context.get("toBalance") + context.get("difference"));
}).commit();
}
int foundMoney = 0;
for (int j = 0; j < numberAccounts; j++) {
Integer foundMoney1;
String account = String.format("account%d", j);
foundMoney1 = database.get(account);
foundMoney += foundMoney1;
}
return foundMoney;
}
}));
}
List<Integer> monies = new ArrayList<>();
for (Future f : futures) {
int foundMoney = (Integer) f.get();
monies.add(foundMoney);
}
System.out.println("Totals while running");
for (Integer money : monies) {
System.out.println(money);
}
System.out.println("Expected money");
System.out.println(totalMoney);
System.out.println("Final money");
int foundMoney = 0;
for (int j = 0; j < numberAccounts; j++) {
Integer foundMoney1;
foundMoney1 = database.get(String.format("account%d", j));
System.out.println(String.format(String.format("account%d %d", j, foundMoney1)));
foundMoney += foundMoney1;
}
System.out.println(foundMoney);
executor.shutdown();
}
private Transaction beginTransaction(List<Transaction> transactions, Map<String, Integer> database) {
transactionCount = transactionCount + 1;
Transaction transaction = new Transaction(transactions, transactionCount, database);
this.transactions.add(transaction);
return transaction;
}
private class Transaction {
public Long readTimestamp = 0L;
public Long writeTimestamp = 0L;
public List<String> readTargets = new ArrayList<>();
private List<Transaction> transactions;
private final int id;
private Map<String, Integer> database;
private List<TransactionStep> steps = new ArrayList<>();
private TransactionContext transactionContext = new TransactionContext();
private boolean active = true;
private boolean cancel = false;
private long transactionFinish;
private long transactionStart;
private int reread;
private boolean valid;
public Transaction(List<Transaction> transactions, int id, Map<String, Integer> database) {
this.transactions = transactions;
this.id = id;
this.database = database;
}
public Transaction read(String field, String name, Function<TransactionContext, String> keyGetter) {
ReadStep step = new ReadStep(this, field, keyGetter);
steps.add(step);
transactionContext.registerStep(name, step);
return this;
}
public Transaction write(String fieldName, Consumer<WriteContext> writer) {
steps.add(new WriteStep(this, fieldName, writer));
return this;
}
public boolean invalid() {
long largestWrite = 0L;
long largestRead = 0L;
List<Transaction> cloned = new ArrayList<>(transactions);
cloned.sort(new Comparator<Transaction>() {
@Override
public int compare(Transaction o1, Transaction o2) {
return (int) (o1.transactionStart - o2.transactionStart);
}
});
for (Transaction transaction : cloned) {
ArrayList<TransactionStep> clonedSteps = new ArrayList<>(transaction.steps);
for (TransactionStep step : clonedSteps) {
for (TransactionStep thisStep : steps) {
if (step instanceof ReadStep && thisStep instanceof ReadStep) {
ReadStep thisReadStep = (ReadStep) thisStep;
ReadStep readStep = (ReadStep) step;
if (thisReadStep.key.equals(readStep.key)) {
if (thisReadStep.timestamp > readStep.timestamp) {
return true;
}
}
}
if (step instanceof WriteStep && thisStep instanceof WriteStep) {
WriteStep thisWriteStep = (WriteStep) thisStep;
WriteStep writeStep = (WriteStep) step;
if (thisWriteStep.timestamp > writeStep.timestamp) {
return true;
}
}
}
}
}
return false;
}
public void commit() {
boolean needsRunning = true;
int retryCount = 0;
transactionStart = System.nanoTime();
while (needsRunning || invalid()) {
readTimestamp = 0L;
writeTimestamp = 0L;
readTargets.clear();
retryCount++;
active = true;
for (TransactionStep step : steps) {
step.run(transactionContext);
}
needsRunning = false;
if (cancel) {
needsRunning = true;
cancel = false;
}
}
System.out.println(String.format("Retry count was %d", retryCount));
for (TransactionStep step : steps) {
if (step instanceof ReadStep) {
String key = ((ReadStep) step).key;
Integer value = transactionContext.context.get(key);
database.put(key, value);
}
}
transactions.remove(this);
transactionFinish = System.nanoTime();
}
}
private interface TransactionStep {
TransactionContext run(TransactionContext context);
}
private class ReadStep implements TransactionStep {
private final String field;
private final Function<TransactionContext, String> keyGetter;
private boolean activated;
private String key;
public long timestamp;
Transaction transaction;
public ReadStep(Transaction transaction, String field, Function keyGetter) {
this.transaction = transaction;
this.field = field;
this.keyGetter = keyGetter;
this.activated = false;
}
public TransactionContext run(TransactionContext context) {
if (!activated) {
key = (String) this.keyGetter.apply(context);
}
activated = true;
timestamp = System.nanoTime();
context.put(field, database.get(key));
if (transaction.readTimestamp == 0L) {
transaction.readTimestamp = timestamp;
}
transaction.readTargets.add(key);
return context;
}
}
private class TransactionContext {
public final HashMap<String, Integer> context;
private Map<String, ReadStep> readSteps = new HashMap<>();
public TransactionContext() {
this.context = new HashMap<>();
}
public void registerStep(String name, ReadStep readStep) {
readSteps.put(name, readStep);
}
public void put(String field, Integer integer) {
this.context.put(field, integer);
}
public String lookupName(String name) {
return readSteps.get(name).key;
}
public void write(WriteStep writeStep, String name, Integer newValue) {
String key = lookupName(name);
writeStep.key = key;
context.put(key, newValue);
}
public Integer get(String field) {
return this.context.get(field);
}
}
private class WriteStep implements TransactionStep {
public String key;
private boolean activated;
private String fieldName;
private final Consumer<WriteContext> writer;
public long timestamp;
Transaction transaction;
public WriteStep(Transaction transaction, String fieldName, Consumer<WriteContext> writer) {
this.transaction = transaction;
this.fieldName = fieldName;
this.writer = writer;
activated = false;
}
@Override
public TransactionContext run(TransactionContext context) {
timestamp = System.nanoTime();
transaction.writeTimestamp = timestamp;
writer.accept(new WriteContext(this, context));
activated = true;
return context;
}
}
private class WriteContext {
private final WriteStep writeStep;
private final TransactionContext context;
public WriteContext(WriteStep writeStep, TransactionContext context) {
this.writeStep = writeStep;
this.context = context;
}
}
}
我收到的输出:
Retry count was 4511
Retry count was 671
Retry count was 5956
Retry count was 140
Retry count was 3818
Retry count was 3102
Retry count was 34
Retry count was 580
Retry count was 106
Retry count was 46
Retry count was 22
Retry count was 11478
Retry count was 199
Retry count was 33
Retry count was 715
Retry count was 263
Retry count was 6186
Retry count was 6846
Retry count was 7012
Retry count was 301
Retry count was 93
Retry count was 148
Retry count was 11
Retry count was 355
Retry count was 7
Totals while running
1000
1000
1000
1000
1000
Expected money
1000
Final money
account0 200
account1 700
account2 100
account3 0
account4 0
1000
BUILD SUCCESSFUL in 515ms
如何提高效率?我敢肯定,Postgres不允许交易在批准之前运行数千次。
transaction.read("fromBalance", "fromAccountName", (context) -> {
int fromAccount = getRandomNumberInRange(0, 4);
String fromAccountName = String.format("account%d", fromAccount);
return fromAccountName;
})
最佳答案
从问题中扣除并查看代码,对测试系统的简短描述:
Map<String,Integer>
。 BankAccounts
解决原子转移的问题。这排除了测试代码,但解决了一致性问题。
public class BankAccounts {
/**
* The number of retries for each transfer
*/
public static final int RETRIES = 10;
/**
* The account database
*/
private Map<String, AtomicInteger> accounts = new HashMap<>();
/**
* Creates accounts with each 200 initial balance.
*/
public BankAccounts() {
// fill the accounts initially
// Left as an exercice to the reader
}
/**
* Return a set with all account names.
*/
public Set<String> accountNames() {
return Collections.unmodifiableSet(accounts.keySet());
}
/**
* Get the balance value for the specified account.
*/
public int getBalanceFor(String accountName) {
AtomicInteger account = accounts.get(accountName);
return account != null ? account.get() : 0;
}
/**
* Atomically transfers an amount from one account to another and returns {@code true} if that was successful.
*/
public boolean transfer(String fromAccountName, String toAccountName, int amount) {
AtomicInteger fromBalance = accounts.get(fromAccountName);
AtomicInteger toBalance = accounts.get(toAccountName);
if (amount < 0 || fromBalance == null || toBalance == null) {
return false;
}
for (int retry = 0; retry < RETRIES; retry++) {
int fromValue = fromBalance.get(); // get from-account balance value
if (fromValue >= amount) { // check if enough money
if (fromBalance.compareAndSet(fromValue, fromValue - amount)) {
toBalance.addAndGet(amount); // Adding money is always allowed ;-)
return true;
} else {
// value of fromBalance was changed concurrently
Thread.yield(); // optional.
}
}
}
return false;
}
}
关于java - 没有锁,是否可以快速解决多线程银行帐户问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64291915/
我有一个 if 语句,如下所示 if (not(fullpath.lower().endswith(".pdf")) or not (fullpath.lower().endswith(tup
然而,在 PHP 中,可以: only appears if $foo is true. only appears if $foo is false. 在 Javascript 中,能否在一个脚
XML有很多好处。它既是机器可读的,也是人类可读的,它具有标准化的格式,并且用途广泛。 它也有一些缺点。它是冗长的,不是传输大量数据的非常有效的方法。 XML最有用的方面之一是模式语言。使用模式,您可
由于长期使用 SQL2000,我并没有真正深入了解公用表表达式。 我给出的答案here (#4025380)和 here (#4018793)违背了潮流,因为他们没有使用 CTE。 我很欣赏它们对于递
我有一个应用程序: void deleteObj(id){ MyObj obj = getObjById(id); if (obj == null) { throw n
我的代码如下。可能我以类似的方式多次使用它,即简单地说,我正在以这种方式管理 session 和事务: List users= null; try{ sess
在开发J2EE Web应用程序时,我通常会按以下方式组织我的包结构 com.jameselsey.. 控制器-控制器/操作转到此处 服务-事务服务类,由控制器调用 域-应用程序使用的我的域类/对象 D
这更多是出于好奇而不是任何重要问题,但我只是想知道 memmove 中的以下片段文档: Copying takes place as if an intermediate buffer were us
路径压缩涉及将根指定为路径上每个节点的新父节点——这可能会降低根的等级,并可能降低路径上所有节点的等级。有办法解决这个问题吗?有必要处理这个吗?或者,也许可以将等级视为树高的上限而不是确切的高度? 谢
我有两个类,A 和 B。A 是 B 的父类,我有一个函数接收指向 A 类型类的指针,检查它是否也是 B 类型,如果是将调用另一个函数,该函数接受一个指向类型 B 的类的指针。当函数调用另一个函数时,我
有没有办法让 valgrind 使用多个处理器? 我正在使用 valgrind 的 callgrind 进行一些瓶颈分析,并注意到我的应用程序中的资源使用行为与在 valgrind/callgrind
假设我们要使用 ReaderT [(a,b)]超过 Maybe monad,然后我们想在列表中进行查找。 现在,一个简单且不常见的方法是: 第一种可能性 find a = ReaderT (looku
我的代码似乎有问题。我需要说的是: if ( $('html').attr('lang').val() == 'fr-FR' ) { // do this } else { // do
根据this文章(2018 年 4 月)AKS 在可用性集中运行时能够跨故障域智能放置 Pod,但尚不考虑更新域。很快就会使用更新域将 Pod 放入 AKS 中吗? 最佳答案 当您设置集群时,它已经自
course | section | type comart2 : bsit201 : lec comart2 :
我正在开发自己的 SDK,而这又依赖于某些第 3 方 SDK。例如 - OkHttp。 我应该将 OkHttp 添加到我的 build.gradle 中,还是让我的 SDK 用户包含它?在这种情况下,
随着 Rust 越来越充实,我对它的兴趣开始激起。我喜欢它支持代数数据类型,尤其是那些匹配的事实,但是对其他功能习语有什么想法吗? 例如标准库中是否有标准过滤器/映射/归约函数的集合,更重要的是,您能
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 这个问题似乎与 help center 中定义的范围内的编程无关。 . 关闭 9 年前。 Improve
我一直在研究 PHP 中的对象。我见过的所有示例甚至在它们自己的对象上都使用了对象构造函数。 PHP 会强制您这样做吗?如果是,为什么? 例如: firstname = $firstname;
...比关联数组? 关联数组会占用更多内存吗? $arr = array(1, 1, 1); $arr[10] = 1; $arr[] = 1; // <- index is 11; does the
我是一名优秀的程序员,十分优秀!