Question about synchronizing two methods...

i have 2 methods:
writeData() //method 1
createNewDataFile() //method 2
the main thread will be using method 1 quite frequently. In method 2, a separate thread will be waking up every 10 minutes or so and doing some maintenance on the file written to in method 1. So, when the thread is in method 2 i need method 1 to standby and wait. I also want the opposite, that when the main thread is in method 2 method 1 will stand by.
Any help is appreciated!

799454 wrote:
So wait,
i thought synchronized only worked on the actual methods where it is declared:Using the synchronized keyword obtains a lock. Each object has exactly one lock associated with it. Once a thread has obtained an object's lock, no other thread can obtain that lock (and hence cannot enter a sync block on that lock) until the first thread releases it by leaving its sync block or calling wait().
so, you're saying that if i declare:
synchronized method 1
synchronized method 2
then i have a single object with 2 synchronized methods, so if thread A is in EITHER of those methods, the other method will be locked as well?The method isn't "locked" per se, but yes, 1 object, 2 synced methods, if T1 is in either method, then T2 cannot enter either method.
I strongly urge you to go through that tutorial and/or a book on Java concurrency, thoroughly.

Similar Messages

  • A question about the getProperty method defined in the Security class

    Hello Everyone!
    I would like to ask a question about the getProperty method defined in the
    Security class.
    public static String getProperty(String key) Do you know how can I exract the list of all possible keys?.
    Thanks in advance,

    I found the answer, in fact the keys are defined in the java.security file.

  • Question about "synchronized" and "wait"

    Hello, everyone!
    I have seen a piece of code like this,
    synchronized (lock)
    //do operation 1
    lock.wait();
    //do operation 2
    I think in the above piece of code, when a thead finished operation 1, it will release the lock and let other threads waiting for the lock have chance to run the same block of code. Am I correct?
    If I am correct, I have a further question, a "synchronized" block means a set of operations that can not be interrupted, but when invoke "wait" method, the thread running in the "synchronized" block will be terminated (interrupted) by release the lock and other threads will have chance to enter the "synchronized" block. In short, the execution inside the "synchronized" block will be interrupted. So, I wonder whether the above piece of code is correct and conforms to the principle of "synchronized". And what is its real use?
    Thanks in advance,
    George

    Thanks, pkwooster buddy!You're welcome
    I just wondered whether "wait inside a synchronized
    block" technology is thread safe. Please look at the
    following example,wait and synchronized are thread safe.
    public class Foo {
    int mVal= 0;
    public final Object mLock = ...;
    public void doIt() {
    synchronized(mLock) {
    mVal = ...;
    mLock.wait();
    if (mVal == ...) {
    // do something
    } else {
    // do something else
    }If we have two threads, T1 and T2, enter the block in
    their respective order, and T1 is woken up first, T2
    may have tampered with T1's execution path because T2
    changed mVal while T1 was asleep. So T2 manipulate
    instance field mVal is a side-effect.when you do the wait() you give up the lock and the other threads get a chance to run. When you exit the wait() you get the new value of the myVal variable which may have been changed. This is exactly what you want. To make that not thread save you could do
    int temp = myVal;
    wait();
    if(temp == ...)in this case the variable temp contains the old vale of myVal.
    >
    I think the most safest way is never wait inside a
    synchronized block, but it is less efficient. What do
    you think about the trick of wait inside a
    synchronized block? I think you are very experienced
    in thread field from your kind reply.
    Thanks in advance,
    Georgewait(), notify() and notifyAll() are very useful. You need them when you want threads to cooperate in an predictable manner. I recommend that you review the section on consumer and producer classes and wait and notify in the Threads Tutorial. It gives good examples. For a practical example of this you could also take a look at my Multithreaded Server Example. It implements a simple chat server that switches String messages. Look especially at the send(), doSend() and popMessage() methods in the StreamConnection class. These allow the receive thread of one user to send messages out using the send thread of another user. If you have questions about that example, please post the questions on that topic.
    Hope this helps.

  • Question about synchronization the methods that work with Properties

    Hello everyone
    I have the following problem with the properties file and synchronization.
    I read properties after the programm was started. And If the properties exist the programm load the properties (java.util.Properties) from the properties file.
    Than I have make the possibility to change this properties in GUI and save it. That mean that the properties file will be used from two plases: the first at the beginning and the second in GUI.
    I wrote the wrapper for properties, say ApplicationProperties.
    I defined ApplicationProperties as the Singleton. At this file I defined
    setters/getters for my variables. This class has also two methods
    load properties or save properties. This two methods work with the propertiesFile the instance of java.io.File.
    The first reads the properties with FileInputStream and the second save it to this file with the FileOutpuStream.
    My question is, do I need to synchronize this two methods to make it thread save?
    private File propertiesFile;
    private void loadPropertiesFromFile() throws FileNotFoundException, IOException {
         FileInputStream input = null;
         try {
              input = new FileInputStream(this.propertiesFile);
              this.properties.load(input);
              updateSettingsFromProperties();
         } catch (FileNotFoundException fnfE) {
              throw new FileNotFoundException("Cannot find the properties file.");
         } catch (IOException ioE) {
              throw new IOException("Cannot read properties file.");
         } finally {
              if(input != null) {
                   input.close();
    private void savePropertiesToFile() throws IOException {
         FileOutputStream out = null;
         try {
              out = new FileOutputStream(this.propertiesFile);
              this.properties.save(out, PROPERTIES_DESCRIPTION);
         } catch (IOException io) {
              throw new IOException("Can't save properties.");     
         } finally {
              if(out != null) {
                   out.close();     
    }Thanks a lot for your advise!

    Will you ever be reading or writing the same file from multiple threads at once?
    Synchronisation can prevent this from happen, but does it ever happen at the moment?

  • Question about synchronized static function.

    Hi, everyone!
    The synchronized statement often deals with an object (called monitor).
    But a static function can be invoked without an object.
    So if a static function is declared as static, what is the function of
    static and synchronized here? Which lock it is using?
    Can you give me a simple expplanation?
    regards,
    George

    Hence try and avoid synchronizing static methods.
    Try and use non static method if you are doing
    multithreaded programming. That way you can have lockWell, I avoid static methods, not just when doing multithreading, but not for the reason you mention.
    objects which allow non interfering methods to be
    accessed in parallelThats easy to do with static methods anyway:
    class Foo
      static Object lock1 = new Object();
      static Object lock2 = new Object();
      static void method1()
         synchronized( lock1 )
      static void method2()
         synchronized( lock2 )
    }Maybe I just missunderstod you...

  • Question about synchronized

    Hello everyone,
    Suppose I have a method which is a synchronized method (for example, method Foo in the following code block), and in this synchronized method another method which is not synchronized is invoked (for example, method Goo in the following code block). I am wondering when executing in Goo from Foo, whether we still have the synchronized feature (i.e. obtain the lock of "this" object).
    synchronized public Foo()
        Goo();
    private Goo()
    }Thanks in advance,
    George

    Kaj,
    Hi, pls see my post above - I replied to the same question in the other forum and I was pretty sure about my answer until I found it different from ur reply here.
    Here is my reply. Can u kindly guide me to what's wrong in it ?
    if a lock on a sync-ed method extends to all methods being called from it, then the jvm (bcos it has no means of knowing until runtime the method calls from a sync method) has to lock all the methods in a class that has atleast one sync method.
    What this would mean potentially is that the effect of sync-ing one method would be equal to sync-ing all the methods bcos any of the other methods could be potentially called from the sync-ed one.
    The example below is co-erced, but serves to illustrate the point.
         public class Test
        synchronized public  void Foo()
            Goo();
        synchronized public  void Moo()
            Goo();       
            notify();
        private void Goo()
            System.out.println(Thread.currentThread().getName()+" accessing goo");
            try
                if(Thread.currentThread().getName().equals("Th one"))
                     //force thread1 to wait , lets see if thread2 can access it while thread1's waiting on it
                    wait();
            catch(Exception e){}
            System.out.println(Thread.currentThread().getName()+" returning from goo");
    //first thread
    public class MyT implements Runnable
        Test t;
        public MyT(Test t)
            this.t = t;
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
        public void run()
            t.Foo();
    //second thread
    public class MyT2 implements Runnable
        Test t;
        public MyT2(Test t)
            this.t = t;
        /* (non-Javadoc)
         * @see java.lang.Runnable#run()
        public void run()
            t.Moo();
    //Main
    public class Main
        public static void main(String[] args)
            Test t = new Test();
            Thread th = new Thread(new MyT(t),"Th one");
            Thread th1 = new Thread(new MyT2(t), "Th two");
            th.start();
            th1.start();       
    And the o/p I got was
    Th one accessing goo/*thread one in goo, is in wait() coz of the funny if clause there*/
    Th two accessing goo /*there's no lock on goo, else with thread one in wait(), this wouldve been impossible*/
    Th two returning from goo/*Thread 2 is over with Goo(), will go back and notify Thread 1*/
    Th one returning from goo/*Thread 1 is notified, wakes up and returns :-)*/
    tx,
    ram.

  • Question about synchronized re-entry

    Suppose I have the following code:
    * method performs actions that require synchronization on state but
    * the programmer ensures manually that it is only called in a context
    * where we are already synchronized on state
    private void veryPrivateMethod() {
        //synchronized(state) { (*) required?
        if (state == 999) {
            // perform actions that require synchronization on state
    public void anotherMethod() {
        synchronized(state) {
            if (state == 42)
                state = 43;
            veryPrivateMethod();
    }See (*): If I ensure manually that veryPrivateMethod will only be called in a context where we are already synchronized on state, do I still need to specifically synchronize on state in the method (reentrant synchronization), or will it be better performance-wise and still safely synchronized if I omit the synchronized statement in veryPrivateMethod()?
    Thanks!

    gimbal2 wrote:
    932196 wrote:
    I synchronize on it whenever I change / compare-change it. Is this a bad ideaThat's a maybe. Its not a bad idea, as long as you realize that doing this has no special meaning and will offer no special protection. You can synchronize on just about any object you want, as long as other threads synchronize on the exact same object when wanting to execute the same section(s) of volatile code.the comment in the example is:
    // perform actions that require synchronization on statethis leads me to believe that the code is not correctly synchronized currently. like i said, changing the reference to the object you are synchronizing on pretty much always leads to broken code.

  • Question about synchronized singleton classes

    Hi,
    I have a singleton class, with only 1 method (which is static), I want access to that method to be synchronized, but someone suggested that I make my getInstance() method synchronized as well.
    Is this neccessary, or is it overkill?
    thanks!

    Example:
    static Instance getInstance() {
    if (instance == null) {
    instance = new Instance();
    return instance;
    }Two threads call it simultaneously:
    1. if (instance == null) { // evaluates true
    2. if (instance == null) { // evaluates true
    1. instance = new Instance(); // first instance
    2. instance = new Instance(); // second instance,
    deleting the reference to the first instance
    1. return instance; // which is not the originally
    created one but the second instance
    2. return instance;There's actually a worse consequence.
    1) T1 sees null
    2) T1 sets instance to point to where the object will live
    4) T2 sees non-null
    3) T2 returns, with a pointer to what's supposed to be an object, but isn't yet inited.
    4) T1 eventually inits the instance
    This can happen even if you use the "double check locking" pattern of synchronization.
    At least under the old memory model. I think the new JMM in effect in 5.0 (and possibly later 1.4) versions fixes it. I don't know if the fact that it can happen in absence of sync/DCL is an error or not, so I'm not sure if that's addressed in the new JMM, or if it's only the synced case that was a bug. (That is, it might be okay that it happens without syncing.)

  • A question about synchronized Lists...

    If I have a synchronized list, and I have a synchronized block in one thread with a lock on that list (synchronized(List)) am i supposed to be able to add an item to that list directly (using the List.add() method) from another thread while I'm still in the synchronized block previously described?
    I have some code here where I tried to test that and the answer that I got is that it is possible while (I believe) it's not possible theoretically speaking.
    import java.util.*;
    public class Warehouse implements Runnable{
         List<String> items = Collections.synchronizedList(new ArrayList<String>());
    //     List<String> items = new ArrayList<String>();
         public static void main(String[] args){
              Warehouse w = new Warehouse();
              Manager m = new Manager(w);
              Thread one = new Thread(w);
              Thread two = new Thread(m);
              one.start();
              two.start();
         public void add(String t){
              synchronized(items){               
                   for(int i=0; i<2; ++i){
                        System.out.println("Warehouse added item...");
                        try{
                        Thread.sleep(500);
                        }catch(InterruptedException ie){
                             ie.printStackTrace();
                   items.add(t);
                   items.notify();
         public void run(){
              for(int i=0; i<1; ++i){
                   synchronized(items){
                        while(items.isEmpty()){
                             try{
                             System.out.println("Warehouse waiting...");
                             items.wait();
    //                         System.out.println("Warehouse after waiting...");
                             for(int j=0; j<2; ++j){
                                  System.out.println("Warehouse after waiting...");
                                  try{
                                  Thread.sleep(500);
                                  }catch(InterruptedException ie){
                                       ie.printStackTrace();
                             }catch(InterruptedException ie){
                                  ie.printStackTrace();
    class Manager implements Runnable{
         Warehouse w;
         public Manager(Warehouse w){
              this.w = w;
         public void run(){
              for(int i=0; i<1; ++i){               
                   System.out.println("Manager Adding item...");
                   w.add("articulo");                              
                   for(int j=0; j<5; ++j){
                        w.items.add("jeje");
                        try{
                        Thread.sleep(500);
                        }catch(Exception ex){ex.printStackTrace();}
                        System.out.println("Manager adding to items");
                   System.out.println("Manager finished with warehouse...");
    }Output:
    Warehouse waiting...
    Manager Adding item...
    Warehouse added item...
    Warehouse added item...
    *Warehouse after waiting...*
    *Manager adding to items*
    *Warehouse after waiting...*
    *Manager adding to items*
    Manager adding to items
    Manager adding to items
    Manager adding to items
    Manager finished with warehouse...The code in "bold" (with the tokens) isn't supposed to happen concurrently as I understand it since the "warehouse after waiting" statement it's in the synchronized block with a lock on the items list and the "manager adding to items" statement is adding an item to that list through a direct reference to that list...

    When the manager thread notifies the items (warehouse thread), the warehouse thread does not have to wake up automatically, it has to compete for the items lock then wait for its Thread context to execute. Which means that the manage is able to continue to execute - adding to items manually, and eventually sleep()ing. When the manager thread sleeps that is a good place for a Thread context switch, and if the JVM takes that opportunity to do so, then the warehouse thread regains the lock and would prevent further access to items. But at some point the Thread context will switch again (probably when warehouse thread goes to sleep). Now the manager thread can wake up, print that it is working because that code is not protected by any synchronized lock. Then when it attempts to add to items again it blocks. Another thread context switch allows the warehouse to complete its work, finish up, and release the items lock. Manager can then get the lock on items and finish its work. The results would be exactly as you display them. Here is a possible walk-through of the threading paths taken:
    Thread == Warehouse
    i = 0
      lock on items
        items.isEmpty == true
          print "Warehouse is waiting"
          items.wait (unlock items)
    /* CONTEXT SWITCH */
    Thread == Manager
    i = 0
      print ""Manager Adding item..."
      locking items
        i = 0
          printing "Warehouse added item..."
          sleeping 500
        i = 1
          printing "Warehouse added item..."
          sleeping 500
        i ! < 2
        locking items
          adding to items
        unlocking items
        notifying items (wait will unlock eventually)
      unlocking items
      j = 0
        locking items
          adding to items
        unlocking items
        sleeping 500
    /* CONTEXT SWITCH */
    Thread == Warehouse
          items.wait (regain lock and get context)
          j = 0
            prinitng "Warehouse after waiting..."
            sleeping 500
    /* CONTEXT SWITCH */
    Thread == Manager
        sleeping 500 is done
        printing "Manager adding to items"
      j = 1
        locking items (blocking until items is available)
    /* CONTEXT SWITCH */
    Thread == Warehouse
            sleeping 500 is done
          j = 1
            printing "Warehouse after waiting..."
          j ! < 2
        itemse ! isEmpty
      unlocking items
    i ! < 1
    /* End of Warehouse Thread */
    /* CONTEXT SWITCH */
    Thread == Manager
        locking items (lock available)
          adding to itemes
        unlock items
        sleeping 500
        printing "Manager adding to items"
      j = 2
        locking items
          adding to itemes
        unlock items
        sleeping 500
        printing "Manager adding to items"
      j = 3
        locking items
          adding to itemes
        unlock items
        sleeping 500
        printing "Manager adding to items"
      j = 4
        locking items
          adding to itemes
        unlock items
        sleeping 500
        printing "Manager adding to items"
      j ! < 5
      printing "Manager finished with warehouse..."
    i ! < 1
    /* End of Manager Thread */So the theory an practice are the same - you can not access the items object when it is locked by another thread. The problem is that your test does not demonstrate when locks are held and released - some of the output you expect to be protected is not and so you mis-interpret the code.

  • Trivial Lock Question - nested synchronized instance method call

    Hi there. I have a question surrounding the following code block:
            public synchronized void bow(Friend bower)
                System.out.format("%s: %s has bowed to me!%n",
                        this.name, bower.getName());
                bower.bowBack(this);
            public synchronized void bowBack(Friend bower)
                System.out.format("%s: %s has bowed back to me!%n",
                        this.name, bower.getName());
            }If the bow method is invoked by the currently executing thread that has obtained the lock on the current instance and the
    call "bower.bowBack()" is invoked, what happens? Is the lock released then obtained again by the current thread? or does it hold onto it since the method
    "bowBack" is called within the method "bow"?
    Thank you!
    Regards

    thank you as always mr. verdagen!
    regards

  • Question about syncing two different iPads on 1 iMac?

    Hey all, I bought two iPad 2's today (both gifts, 1 for my mom and 1 for my dad). Bought it for them because they're probably too old at this stage for me to teach them to use a desktop efficiently. iPad is so easy for them to use the internet and listen to their music which is most important.
    My question is, I don't have an iPad myself nor any iOS devices. Maybe I'll buy an ipad in a few months or so. However I do own the only computer in the house and that's my iMac. I was going to sync both my mom and dad's iPads to my Mac, and put their songs from my iTunes library on their iPads respectively. Will I incure any problems trying to do this?
    I don't want my mom and dad's iPads to be identical and I want to sync different pictures and songs and stuff on their ipads. I want it to be their own individually.
    What steps should I take to do this? I've never really synced any iOS products before but I pick up on this stuff pretty quickly. Made the transition from a Windows desktop to a Mac easily and would do it all over again!

    Have a read here...
    https://discussions.apple.com/message/18409815?ac_cid=ha
    And See Here...
    How to Use Multiple iDevices with One Computer

  • Question about tunnel two WLAN from the same foreign WLC to the same anchor

    Hi all,I met following customer request:
    one anchor WLC 4402-12 put in the DMZ of perimeter firewall, one WiSM in the internal network to controll all the AP1252. two WLAN created at the WiSM and anchor WLC: guest wlan(web-auth+lobby admin created guest accounts) and untrusted wlan(web-auth+ACS+AD user database). Both WLANs want to be tunneled from WiSM to Anchor WLC. Guest WLAN has not much users, untrusted WLAN has a lot of users which may be thousands. My question is if this design can work?(I know definately one WLAN can be tunneled, but not sure if there's any potential issues if tunnel two WLANs)
    Is there any performance issue? What WLC version is suggested to use?
    Thanks for any help!

    I haven't ever tried this but suspect that you can form only one tunnel outbound per WLC. The anchor supports multiple inbound tunnels but outbound is the question. When you find out for sure please post it here.

  • Question about connecting two monitors to Mid 2010 MBP

    I have a Mid 2010 MacBook Pro (running OS X, 10.6.8), and I want to connect it to two ASUS monitors (VS228H-P) that have HDMI, DVI, and VGA interfaces.
    1) Is this possible?
    2) What parts will I need to make the connection?
    3) Will I be able to close the lid without the MBP going to sleep?
    4) Any recommendations for an external mouse and clickety-clack keyboard? (My preference is for wireless, but I'm open to wired, too).
    If there are other recommendations for configuration (I'd like to spend less than $150/monitor. They won't be used for gaming, but for working from home and watching various media...)
    THANKS!!!

    Hi kishap8,
    Have you made changes in the display settings to make the PC use both monitors? It doesn't extend the screen on it's own.
    Here is an HP Support document on how to change display settings: http://h10025.www1.hp.com/ewfrf/wc/document?docname=c03366869&cc=us&dlc=en&lc=en&product=5309983
    And here are a couple videos (for Windows 7 that is very similar to Win 8) on how to work with multiple monitors:
    https://www.youtube.com/watch?v=Nj0RT8yVlUA
    https://www.youtube.com/watch?v=WDQCXOSJGM0
    ...an HP employee just trying to help where I can, but not speaking on behalf of HP.

  • Question about suming two columns from different tables in Subquery?

    Hello everyone,
    I have a subquery that works great for getting the total SUM of a Billing table, but I also need to add to that SUM the total surcharges or additional charges from a separate table.  I tried this by doing something like so:
    (SELECT SUM(SUM(Amount) FROM Billing WHERE Billing.JobID = Jobs.ID AND Billing.BillingType = 'Invoice' AND Billing.InvoiceCanceled = 'No', SUM(Payment) FROM Payments WHERE Payments.JobID = Jobs.ID AND Payments.Type = 'Bill')) as [Amount],
    But it doesn't work as there is an incorrect syntax near 'FROM'.  I'm assuming this is because of the two FROM's in the Subquery?  But I am not sure how else I would be able to do this then?  
    Any help would be greatly appreciated.  I just noticed this bug and am hoping to get a fix out as quickly as possible.
    Thanks Again,

    Hi, sorry for taking so long to get back to this post. 
    I tried this example like so:
    (SELECT SUM(A1) AS Total1, SUM(A2) AS Total2
    FROM
    (SELECT
    (SELECT SUM(Amount) FROM Billing WHERE Billing.JobID = Jobs.ID AND Billing.BillingType = 'Invoice' AND Billing.InvoiceCanceled = 'No') AS A1,
    (SELECT SUM(Payment) FROM Payments WHERE Payments.JobID = Jobs.ID AND Payments.Type = 'Bill') AS A2),
    However, get an error that an Incorrect Syntax exists near the ','.  I remove the comma (Which I think should be there), and I get an error that an Incorrect Syntax exists near the '.'...
    I also tried doing it like this (Based on other suggestions I've found online:
    (SELECT SUM(SELECT SUM(Amount) FROM Billing WHERE Billing.JobID = Jobs.ID AND Billing.BillingType = 'Invoice' AND Billing.InvoiceCanceled = 'No') as [Amount],
    (SELECT SUM(Payment) FROM Payments WHERE Payments.JobID = Jobs.ID AND Payments.Type = 'Bill') as [Additional]),
    And I get an error that an Incorrect Syntax exists near 'SELECT'...
    I also tried doing something like this with the SQL I already had...
    (SELECT SUM(Amount) FROM Billing WHERE Billing.JobID = Jobs.ID AND Billing.BillingType = 'Invoice' AND Billing.InvoiceCanceled = 'No') as [BilledAmount],
    (SELECT SUM(Payment) FROM Payments WHERE Payments.JobID = Jobs.ID AND Payments.Type = 'Bill') as [Additional],
    SUM(BilledAmount + Additional) AS [TotalBilled],
    But I get an error that the alias' are Invalid Column Names...  I have used Alias' before so I'm not sure why this would be an issue here...
    As you can see, I've been trying to figure this issue out, but haven't had much luck...  :(

  • Questions about these two IO classes....

    1)
    OutputStreamWriter
    An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.
    i dont understand. Converting characters into bytes is understandable, but what does it mean by "using specified charset"?? I mean, isn't that the other way around?? ie, you convert bytes into characters using a specified charset??
    2)
    BufferedWriter, BufferedWhatEver...
    What does that makes code cleaner, when OutputStreamWriter and PrintWriter have basically same methods as they do??
    3)
    For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations. For example:
    Writer out
    = new BufferedWriter(new OutputStreamWriter(System.out));
    What does it mean by "to avoid frequent converter invocations"?
    thanks for any responses.

    so, what is "buffering" then?
    I dont understand the explanation... lower code
    invocation??
    maybe in a plainer sentence will help??
    so sorry for not understand it.The following is not necessarily accurate in every technical detail, but it's close enough to demonstrate the principles.
    Let's say I'm going to write 10 bytes. I can do this: stream.write(b0);
    stream.write(b1);
    stream.write(b9);Each of those will cause stream to acces whatever native code it uses which will cause an I/O operation to happen at the hardware level--it will write a byte to the disk controller. It will do this once for every byte.
    Doing that physical I/O carries an overhead. The time taken to actually get the one byte written may be vastly overshadowed by the time taken to access the controller.
    You wouldn't want to establish a connection to a web server, read a byte, close the connection, establish antoher connection, read a byte, et.c. ... right?
    Now, instead, if I put the bytes in an array and call something like bufStream.write(arr, fromByteZero, tenBytes); then I make one call to the stream, it makes one call to the disk controller, pays the overhead cost only once, and writes all ten bytes.
    So instead of 10*overhead + 10*byte_write_time I pay 1*overhead + 10*byte_write_time

Maybe you are looking for