Search code examples
javamultithreadingsynchronize

Static Class with attributes and synchronized methods


I know that there are alot of nearly equal answers here on StackOverFlow but they didn't fit my needs.

Given the following code example:

(inner class)

static class OutgoingFileTransfer implements Runnable {

File sendThisFile;

outgoingFileTransfer(File sendThis) {
    this.sendThisFile = sendThis;
}

@Override
public synchronized void run() {
    //Send the file...  
}

}

I know, that the synchronized method will lock the whole class, but only if the run() method has been called. If I do the following:

Thread a = new Thread(new OutgoingFileTransfer(new File("c:/.../file1"))).start();
Thread b = new Thread(new OutgoingFileTransfer(new File("c:/.../file2"))).start();

Could it be, that Thread a initialises file1 and BEFORE entering the synchronized method, and then Thread b interrupts, set file2 and joins the run() method? This would mean, that file1 never would be sent. Right?

And is there any way to prevent this?

I know the cheap way: Make everything non static an add a boolean iAmCurrentlySendingAFilePleaseWaitInTheQueueTillTheOtherFileTransferFinished, so that all goes sequential. But I think there will be nicer ways to do this. Thanks for your help. :)


Solution

  • Thread a = new Thread(new OutgoingFileTransfer(new File("c:/.../file1"))).start();
    Thread b = new Thread(new OutgoingFileTransfer(new File("c:/.../file2"))).start();
    

    Creates two different threads with two different OutgoingFileTransfer objects. Each will have its own version of sendThisFile and will operate on it. Synchronization and locking come into play when multiple threads act on the same object at the same time. In your case, there is no danger of a race condition, the two threads are independent and run parallely.

    Edit:
    Static Classes in Java:
    Java allows only static inner classes, not static top level classes. A static class does not make everything in it static. From The Java tutorials:

    In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

    So a static class can be instantiated like any other class, can have static and non static members line any other class and the behaviour of static and non static members are like any other class.

    So in your case, there are two sendThisFile independent attributes from teo independent instances of the class. In this case, the behaviour is same as if OutgoingFileTransfer were a top level (therefore non static) class.