multithreading - Java how to limit number of threads acting on method -
i have java method in web application doing heavy file operation. thing is, if more 5 threads come simultaneously (which come in testing phase) breaks down. mean cannot handle heavy traffic.
that's why want handle maximum 5 requests @ time method if 6th request come wait until 1 of first 5 finished
public synchronized void add(int value){ file a=new file("d:/heavyfile1"); file b=new file("d:/heavyfile2"); file c=new file("d:/heavyfile3"); //operation on file } i have added synchronized keyword handles 1 request @ time leading performance issue every next thread have wait till finished. please me.
you can use executor.newfixedthreadpool idiom, internally execution logic.
full example below:
public class main { public static void main(string[] args) throws exception { main m = new main(); // simulating window of time method invoked continuously (int = 0; < 11; i++) { m.dosomething(); } // shutting down executor when done m.terminate(); } executorservice executor = executors.newfixedthreadpool(5); // internally submits new task executor public void dosomething() { executor.submit(new runnable() { @override public void run() { long wait = threadlocalrandom.current().nextlong(2000); try { system.out.printf( "%s sleeping %dms.%n", thread.currentthread().getname(), wait ); thread.sleep(wait); } catch (interruptedexception ie) { // suppressed } system.out.printf( "%s doing something!%n", thread.currentthread().getname() ); } }); } public void terminate() throws exception { executor.shutdown(); } } output
will vary, in lines of:
pool-1-thread-1 sleeping 1533ms. pool-1-thread-4 sleeping 784ms. pool-1-thread-3 sleeping 684ms. pool-1-thread-5 sleeping 1375ms. pool-1-thread-2 sleeping 1717ms. pool-1-thread-3 doing something! pool-1-thread-3 sleeping 1252ms. pool-1-thread-4 doing something! pool-1-thread-4 sleeping 301ms. pool-1-thread-4 doing something! pool-1-thread-4 sleeping 1140ms. pool-1-thread-5 doing something! pool-1-thread-5 sleeping 1454ms. pool-1-thread-1 doing something! pool-1-thread-1 sleeping 1594ms. pool-1-thread-2 doing something! pool-1-thread-2 sleeping 227ms. pool-1-thread-3 doing something! pool-1-thread-2 doing something! pool-1-thread-4 doing something! pool-1-thread-5 doing something! pool-1-thread-1 doing something! note
see re-used thread names, new submitted tasks assigned vacant thread in pool.
Comments
Post a Comment