I completely new to multithreading in Java. But I'm trying to create a method that is multithreaded and thread-safe and below is what I've come up with so far. This method can be called with the same account with either the source or destination arguments in different threads. So for example thread 1 with an account maybe the source, while thread 2 may be the destination of this transfer. Can anyone point me in the right direction. I've looked at this post: Java Multithreading : How to make a thread wait ? and other articles on the web explaining how synchronized works and my assumption is that by putting synchronized around the below code block will lock the process until it has completed. Then the other threads can pick up afterward and process the rest. I apologize in advance for my ignorance on this topic. I'm just hoping someone could put me in the right direction. There's a lot of information to go through and I'm just hoping for some expert guidance. Thanks in advance
public static void transfer(BankAccount source, BankAccount destination, int amount) {
if (source.getAvailableFunds() >= amount) {
synchronized (BankAccount.class) {
source.setAvailableFunds(source.getAvailableFunds() - amount);
destination.setAvailableFunds(destination.getAvailableFunds() + amount);
}
} else {
throw new IllegalArgumentException("No funds in source: " + source);
}
}