سؤال

I m having a server code to process an image.

Now there are n number of requests which tries to execute the code which results in OutOfMemory error or the server to hang and the server goes to not responding state.

To stop the code from executing at once all the requests I m limiting to execute the code one at a time using the below method where i have a variable

if the variable is 10 then wait for the variable to come at 0

if at 0 then set it to 10 then execute the code

run the code and finally set i to 0

The code here -

static newa.Counter cn;

public int getCounta() {

    return cn.getCount();

}

public void setCounta(int i) {
    cn = new newa.Counter();
    cn.setCount(i);

}

at the function i m doing this -

public BufferedImage getScaledImage(byte[] imageBytes)
{
    int i=0;
    Boolean b = false;
    BufferedImage scaledImage = null;
    newa.NewClass1 sc = new newa.NewClass1();
    try {
        sc.getCounta();
    } catch (NullPointerException ne) {
        sc.setCounta(0);
    }

    i = sc.getCounta();

    if(i==0) 
    {
        sc.setCounta(10);
        b = true;
    } 
    else
    {
        while( b == false) 
        {
            try 
            {
                Thread.sleep(2000);
                i = sc.getCounta();
                if( i==0) 
                {
                    sc.setCounta(10);
                    b = true;
                    System.out.println("Out of Loop");
                }
            } catch (InterruptedException ex) {
                System.out.println("getScaledImage Thread exception: " + ex);
            }
        }
    }

    ..... execute further code

    try { } catch { } finally { sc.setCounta(0); }

    }

Is there any way I can have this simplified using the Runnable interface or something as I don't know how to do multi-threading.

هل كانت مفيدة؟

المحلول

Forget about the counter and use a synchronized method. Changed your method head to this:

public synchronized BufferedImage getScaledImage(byte[] imageBytes)

This lets all the threads entering the method wait until no other thread is executing the method.

نصائح أخرى

If you want only a small number of threads doing the processing you can use Executor framework to have a thread pool of 10 threads. This will ensure that at one time maximum of 10 threads will be processing the requests.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top