Results 1 to 4 of 4

Thread: Synchronizing Java program for performance

  1. #1
    Join Date
    Aug 2005
    Posts
    293

    Synchronizing Java program for performance

    Java Synchronization


    I. Introduction :
    Timing is essential in java programming, therefore java uses multiple threads (that is to say in virtually all applications). Indeed, without synchronization, it is impossible to develop a robust application that works regardless of the interleaving of execution threads.

    It is considered that: you know the java syntax, object-oriented programming and general operation threads and the scheduler etc.

    I.A - General Problems:
    Many synchronization problems arise, these are few of them
    1. Several receivers can not simultaneously make work in the line of work, otherwise the work would be on the same box.
    2. If the work queue is full, the receiver must wait for a box becomes available for filing a new job.
    3. Many workers can not take everyone working together, otherwise they would have the same work process.
    4. If the work queue is empty, workers must wait until a job is submitted in order to treat.
    5. Many workers can not simultaneously make the results of an in-line results, otherwise the results would be on the same box.
    6. If the results file is full, the workers must wait for a box becomes available for filing a new result.
    7. If the results file is empty, the sender must wait until a result is available.

    I.B - Objectives
    The goal is to solve these general problems, which can be in most cases be reduced.
    To solve them properly, we must ensure:
    The Safety : Nothing bad happens, whatever the interlacing of threads (two workers can never take the same job)
    The vivacity : Something good finally happen (if the work queue is not empty, a worker would eventually work).

    We must also take into account if possible, for example, two works may be filed consecutively executed sequentially by the same worker.

  2. #2
    Join Date
    Aug 2005
    Posts
    293

    Re: Synchronizing Java program for performance

    II. Mutual exclusion of critical sections
    Mutual exclusion can solve the problems of synchronization 1, 3 and 5 which are in the list of the general problems.

    Here is a sample program that does not meet the security, if multiple threads can simultaneously access:
    Code:
    class Lsttab {
    
        private String[] t = new String[50];
        private int ind = 0;
    
        void adds (Strings) 
    	{
            t [ind] = s;
            ind + +;
        }
    
    }
    This program, as you guessed, allows a list of Strings using a table.
    Code:
    void adds (Strings) 
    {
        tab [ind] = s; / / (a1) 
        ind + +; / / (a2)
    }
    And / Or
    Code:
    void adds (Strings) 
    {
        tab [ind] = s; / / (b1) 
        ind + +;       / / (b2)
    }
    The function adds is called critical section. Several critical sections dependent should never execute their code simultaneously (by several different threads). It is said they are mutual exclusion. In the previous example, adds was mutually exclusive with itself, but of course we can imagine it will also be mutually exclusive with the function removes.

    To implement the mutual exclusion, we must use Locks. When a thread enters a critical section, it requests the lock. If it gets its, it can then execute the code. If it does not get it, because another thread has already taken, then it is blocked waiting to receive it. It is possible to use a potentially infinite number of locks, and then make specific mutual exclusion.

    II.A - Synchronized Keyword:
    To achieve this in Java, the easiest method is to use the keyword synchronized.

    Here's how it is used:
    Code:
    synchronized(Obj) 
    {
        / / critical section
    }
    Obj represents a lock that can be an Java Object. Beware though, it is better to use references reported Final. To be sure that the reference to the object is not changed, in fact, the scenario below does not work, because when multiple threads reach the synchronized block, the variable mlst does not always reference the same object, and therefore is not always the same lock.

    Code:
    synchronized(mlst) 
    {
        mlst = new ArrayList <String>();
    }
    Special case: When the object is lock for synchronization and it includes all the code of a method, you can put the keyword synchronized in the method signature. The two codes below are strictly equivalent:

    Code:
    void method () 
    {
        synchronized(this) {
            / / critical section
        }
    }
    And
    Code:
    synchronized void method () 
    {
        / / critical section
    }
    II.B - Package java.util.concurrent.locks:
    Another method for making locks, appeared in Java 1.5. At first sight it may seem complicated, but it is also more powerful in the sense that it can do things that the keyword synchronized does not.

    Here's how to use it:
    Code:
    Lock lc = newReentrantLock ();
    lc.lock ();
    try {
        / / critical section
    } finally
    {
        lc.unlock ();
    }
    To compare this method with the previous lc.lock () and lc.unlock () correspond to the beginning and end of block synchronized. However, if you wish to mutual exclusion as simple as those examples presented here, I advise you to use synchronized And to reserve this method for special cases.

  3. #3
    Join Date
    Aug 2005
    Posts
    293

    Re: Synchronizing Java program for performance

    III. Cooperative Synchronization:
    Synchronization cooperative solves the problems of synchronization 2, 4, 6 and 7 which are listed in the General problems.

    III.A- Methods of the Object class

    Use:

    The most basic synchronization between multiple threads Java is the use of methods wait () and notify () (and possibly notifyAll ()) defined in class Object. To understand their operation, here is an sample code
    Code:
    class lsttab 
    {
        private String[] t = new String[50];
        private int ind = 0;
    
        synchronized void adds (Strings) {
            t [ind] = s;
            ind + +;
            notify ();
            System.out.println ("notify () executed"); 
        }
    
        synchronized StringgetPremierElement () {
            / / until the list is empty
            while(ind == 0) {
                try {
                    / / passive waiting
                    wait ();
                } catch(InterruptedException e) {
                    e.printStackTrace ();
                }
            }
            return t [0];
        }
    
    }
    The method getPremierElement returns the first element of the list, if the list is empty, and although it looks that there is an added element. You might be surprised by the loop while Method getPremierElement rather than just if.

    Limits:
    Apart from the difficulty of implementation for complex problems, this solution reached its limits therefore a critical section must be synchronized on multiple locks.
    Here is am sample example showing the same:
    Code:
    class SomeClass {
    
        private Final Object lc1 = new Object ();
        private Final Object lc2 = new Object ();
    
        void method () {
            synchronized(lc1) {
                synchronized(lc2) {
                    while(condition) {
                        lc2.wait ();
                    }
                }
            }
        }
    
        void notify () {
            lc2.notify ();
        }
    
    }
    Indeed, to implement the wait () we are forced to choose one of two locks, and then one of them is released during the wait. In this case here, the call method () locks completely lc1 as lc2.wait () was not completed.

    III-B. Package java.util.concurrent.locks:
    The solution we have seen to realize mutual exclusion using this package can also go beyond the boundaries of class methods Object. The principle is to use a single bolt, but with several condition variables (on which we can perform operations similar to wait () and notify ()).
    Here is an sample code for it
    Code:
    class SomeClass {
    
        private Final Lock lc = new ReentrantLock ();
        private Final Condition cd1 = lc.new Condition ();
        private Final Condition cd2 = lc.new Condition ();
    
        void method1 () throws InterruptedException {
            lc.lc ();
            try{
                cd1.await ();
                cd2.signal ();
            } finally{
                lc.unlc ();
            }
        }
    
        void method2 () throws InterruptedException {
            lc.lc ();
            try{
                cd1.signal ();
                cd2.await ();
            } finally{
                lc.unlc ();
            }
        }
    
    }
    Now, calls for cd1.await () and c2.await () release the lock well lock.

    III.C - Threads:
    So far, the word thread pointed to a thread. In this section, the word Thread Class mean Thread Java. The relationship between the two is that the method call start () Class Thread creates a new thread in which code is executed.
    This is not an article on the Thread class, but here are some ways to know:
    - static Thread currentThread () : Obtains the current thread.
    - static void yield () : A chance to let other threads run.
    - static void sleep (long msec) throws InterruptedException : Suspend execution of the calling thread during the specified time
    - void interrupt () : Causes either lift the exception InterruptedException if the activity is blocked on a synchronization operation or placement of an indicator interrupted.
    - void join () : Waiting blocking the termination of the thread of execution

  4. #4
    Join Date
    Aug 2005
    Posts
    293

    Re: Synchronizing Java program for performance

    IV. Solutions implemented in Java 1.5 and greater:

    Version 1.5 of Java and its package java.util.concurrent (and its sub-packages) provide tools for synchronizing the highest level. A useful tool is Executor. There is a waiting list for blocking action to perform. We found exactly the same mechanism when using the thread dedicated to the graphic display (EventDispatchThread) of Swing : SwingUtilities.invokeLater (Runnable) put in the queue an action to perform in the thread dedicated to the graphic display.
    Here is an example of the use of Executor :
    Code:
    Executors.new SingleThreadExecutor Executor executor = ();
    executor.execute (newRunnable () {
        Public void run () {
            System.out.println ("asynchronous call 1");
        }
    }};
    executor.execute (new Runnable () {
        Public voidrun () {
            System.out.println ("asynchronous call 2");
        }
    }};
    This example executes Runnables asynchronously, but ensures that they will be taken in order.


    V. Inter-lock


    The most common problem in synchronization during development is the Inter-lock. An inter-locking (or deadlock) is a deadlock that occurs.

    Here is a simple example of inter-locking:
    Code:
    class DeadLock {
    
        private Final Object lc1 = new Object ();
        private Final Object lc2 = new Object ();
    
        void a() throwsInterruptedException {
            lc1.wait ();
            lc2.notify ();
        }
    
        void b() throwsInterruptedException {
            lc2.wait ();
            lc1.notify ();
        }
    
    }
    If a thread T1 running a () and a thread T2 running b () there will be a inter-lock. Indeed, T1 awaits notify() of T2, but for T2 to call notify () it must first executes T1 for its notify (). It is essential to ensure never have deadlock in your code.


    VI. Avoid unnecessary synchronization

    The timing is something essential in many situations. However, it is expensive in CPU, do not sync everything. If a method can be called only a single thread, do not synchronize. When you use a lot of sync, try to see if the model of a queue does not fit better (Executor), It will simplify a lot more of your code. You can avoid the Vector , Hashtable which are synchronized by default and use the ArrayList , HashMap which are not synchronized by default and best for performance.

Similar Threads

  1. How to run java applet program using cmd
    By Rao's in forum Software Development
    Replies: 3
    Last Post: 07-01-2012, 03:35 PM
  2. Dr. Java program
    By bamggut29 in forum Software Development
    Replies: 2
    Last Post: 26-11-2011, 04:24 AM
  3. Sluggish Program Performance -CPU fluctuations
    By Priscilia in forum Motherboard Processor & RAM
    Replies: 3
    Last Post: 03-03-2011, 04:03 PM
  4. Don't know how to run the java bean program
    By Reema_n in forum Software Development
    Replies: 5
    Last Post: 23-12-2009, 11:01 AM
  5. Link List Example in Java Sample program in Java
    By trickson in forum Software Development
    Replies: 2
    Last Post: 04-08-2009, 08:23 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,713,556,450.74395 seconds with 17 queries