logo

Java Konu Havuzu

Java Konu havuzu işi bekleyen ve birçok kez yeniden kullanılan bir grup çalışan iş parçacığını temsil eder.

Bir iş parçacığı havuzu durumunda, sabit boyutlu bir iş parçacığı grubu oluşturulur. İş parçacığı havuzundan bir iş parçacığı çıkarılır ve servis sağlayıcı tarafından bir iş atanır. İşin tamamlanmasından sonra iş parçacığı tekrar iş parçacığı havuzunda bulunur.

İş Parçacığı Havuzu Yöntemleri

newFixedThreadPool(int s): Yöntem, sabit boyuttaki bir iş parçacığı havuzu oluşturur.

newCachedThreadPool(): Yöntem, gerektiğinde yeni iş parçacıkları oluşturan yeni bir iş parçacığı havuzu oluşturur ancak yine de, kullanıma hazır olduklarında önceden oluşturulan iş parçacığını kullanmaya devam eder.

newSingleThreadExecutor(): Yöntem yeni bir iş parçacığı oluşturur.

Java Konu Havuzunun Avantajı

Daha iyi performans Yeni bir konu oluşturmaya gerek olmadığından zaman kazandırır.

Gerçek zamanlı kullanım

Konteynerin isteği işlemek için bir iş parçacığı havuzu oluşturduğu Servlet ve JSP'de kullanılır.

Java İş Parçacığı Havuzu Örneği

ExecutorService ve Executors'ı kullanan Java iş parçacığı havuzunun basit bir örneğini görelim.

Dosya: WorkerThread.java

dize oluşturucu java
 import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class WorkerThread implements Runnable { private String message; public WorkerThread(String s){ this.message=s; } public void run() { System.out.println(Thread.currentThread().getName()+' (Start) message = '+message); processmessage();//call processmessage method that sleeps the thread for 2 seconds System.out.println(Thread.currentThread().getName()+' (End)');//prints thread name } private void processmessage() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } } 

Dosya: TestThreadPool.java

 public class TestThreadPool { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5);//creating a pool of 5 threads for (int i = 0; i <10; i++) { runnable worker="new" workerthread('' + i); executor.execute(worker); calling execute method of executorservice } executor.shutdown(); while (!executor.isterminated()) system.out.println('finished all threads'); < pre> <p> <strong>Output:</strong> </p> <pre>pool-1-thread-1 (Start) message = 0 pool-1-thread-2 (Start) message = 1 pool-1-thread-3 (Start) message = 2 pool-1-thread-5 (Start) message = 4 pool-1-thread-4 (Start) message = 3 pool-1-thread-2 (End) pool-1-thread-2 (Start) message = 5 pool-1-thread-1 (End) pool-1-thread-1 (Start) message = 6 pool-1-thread-3 (End) pool-1-thread-3 (Start) message = 7 pool-1-thread-4 (End) pool-1-thread-4 (Start) message = 8 pool-1-thread-5 (End) pool-1-thread-5 (Start) message = 9 pool-1-thread-2 (End) pool-1-thread-1 (End) pool-1-thread-4 (End) pool-1-thread-3 (End) pool-1-thread-5 (End) Finished all threads </pre> download this example <h2>Thread Pool Example: 2</h2> <p>Let&apos;s see another example of the thread pool.</p> <p> <strong>FileName:</strong> ThreadPoolExample.java</p> <pre> // important import statements import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.text.SimpleDateFormat; class Tasks implements Runnable { private String taskName; // constructor of the class Tasks public Tasks(String str) { // initializing the field taskName taskName = str; } // Printing the task name and then sleeps for 1 sec // The complete process is getting repeated five times public void run() { try { for (int j = 0; j <= 5; j++) { if (j="=" 0) date dt="new" date(); simpledateformat sdf="new" simpledateformat('hh : mm ss'); prints the initialization time for every task system.out.println('initialization name: '+ taskname + '=" + sdf.format(dt)); } else { Date dt = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(" hh execution system.out.println('time of is complete.'); } catch(interruptedexception ie) ie.printstacktrace(); public class threadpoolexample maximum number threads in thread pool static final int max_th="3;" main method void main(string argvs[]) creating five new tasks runnable rb1="new" tasks('task 1'); rb2="new" 2'); rb3="new" 3'); rb4="new" 4'); rb5="new" 5'); a with size fixed executorservice pl="Executors.newFixedThreadPool(MAX_TH);" passes objects to execute (step 3) pl.execute(rb1); pl.execute(rb2); pl.execute(rb3); pl.execute(rb4); pl.execute(rb5); shutdown pl.shutdown(); < pre> <p> <strong>Output:</strong> </p> <pre> Initialization time for the task name: task 1 = 06 : 13 : 02 Initialization time for the task name: task 2 = 06 : 13 : 02 Initialization time for the task name: task 3 = 06 : 13 : 02 Time of execution for the task name: task 1 = 06 : 13 : 04 Time of execution for the task name: task 2 = 06 : 13 : 04 Time of execution for the task name: task 3 = 06 : 13 : 04 Time of execution for the task name: task 1 = 06 : 13 : 05 Time of execution for the task name: task 2 = 06 : 13 : 05 Time of execution for the task name: task 3 = 06 : 13 : 05 Time of execution for the task name: task 1 = 06 : 13 : 06 Time of execution for the task name: task 2 = 06 : 13 : 06 Time of execution for the task name: task 3 = 06 : 13 : 06 Time of execution for the task name: task 1 = 06 : 13 : 07 Time of execution for the task name: task 2 = 06 : 13 : 07 Time of execution for the task name: task 3 = 06 : 13 : 07 Time of execution for the task name: task 1 = 06 : 13 : 08 Time of execution for the task name: task 2 = 06 : 13 : 08 Time of execution for the task name: task 3 = 06 : 13 : 08 task 2 is complete. Initialization time for the task name: task 4 = 06 : 13 : 09 task 1 is complete. Initialization time for the task name: task 5 = 06 : 13 : 09 task 3 is complete. Time of execution for the task name: task 4 = 06 : 13 : 10 Time of execution for the task name: task 5 = 06 : 13 : 10 Time of execution for the task name: task 4 = 06 : 13 : 11 Time of execution for the task name: task 5 = 06 : 13 : 11 Time of execution for the task name: task 4 = 06 : 13 : 12 Time of execution for the task name: task 5 = 06 : 13 : 12 Time of execution for the task name: task 4 = 06 : 13 : 13 Time of execution for the task name: task 5 = 06 : 13 : 13 Time of execution for the task name: task 4 = 06 : 13 : 14 Time of execution for the task name: task 5 = 06 : 13 : 14 task 4 is complete. task 5 is complete. </pre> <p> <strong>Explanation:</strong> It is evident by looking at the output of the program that tasks 4 and 5 are executed only when the thread has an idle thread. Until then, the extra tasks are put in the queue.</p> <p>The takeaway from the above example is when one wants to execute 50 tasks but is not willing to create 50 threads. In such a case, one can create a pool of 10 threads. Thus, 10 out of 50 tasks are assigned, and the rest are put in the queue. Whenever any thread out of 10 threads becomes idle, it picks up the 11<sup>th </sup>task. The other pending tasks are treated the same way.</p> <h2>Risks involved in Thread Pools</h2> <p>The following are the risk involved in the thread pools.</p> <p> <strong>Deadlock:</strong> It is a known fact that deadlock can come in any program that involves multithreading, and a thread pool introduces another scenario of deadlock. Consider a scenario where all the threads that are executing are waiting for the results from the threads that are blocked and waiting in the queue because of the non-availability of threads for the execution.</p> <p> <strong>Thread Leakage:</strong> Leakage of threads occurs when a thread is being removed from the pool to execute a task but is not returning to it after the completion of the task. For example, when a thread throws the exception and the pool class is not able to catch this exception, then the thread exits and reduces the thread pool size by 1. If the same thing repeats a number of times, then there are fair chances that the pool will become empty, and hence, there are no threads available in the pool for executing other requests.</p> <p> <strong>Resource Thrashing:</strong> A lot of time is wasted in context switching among threads when the size of the thread pool is very large. Whenever there are more threads than the optimal number may cause the starvation problem, and it leads to resource thrashing.</p> <h2>Points to Remember</h2> <p>Do not queue the tasks that are concurrently waiting for the results obtained from the other tasks. It may lead to a deadlock situation, as explained above.</p> <p>Care must be taken whenever threads are used for the operation that is long-lived. It may result in the waiting of thread forever and will finally lead to the leakage of the resource.</p> <p>In the end, the thread pool has to be ended explicitly. If it does not happen, then the program continues to execute, and it never ends. Invoke the shutdown() method on the thread pool to terminate the executor. Note that if someone tries to send another task to the executor after shutdown, it will throw a RejectedExecutionException.</p> <p>One needs to understand the tasks to effectively tune the thread pool. If the given tasks are contrasting, then one should look for pools for executing different varieties of tasks so that one can properly tune them.</p> <p>To reduce the probability of running JVM out of memory, one can control the maximum threads that can run in JVM. The thread pool cannot create new threads after it has reached the maximum limit.</p> <p>A thread pool can use the same used thread if the thread has finished its execution. Thus, the time and resources used for the creation of a new thread are saved.</p> <h2>Tuning the Thread Pool</h2> <p>The accurate size of a thread pool is decided by the number of available processors and the type of tasks the threads have to execute. If a system has the P processors that have only got the computation type processes, then the maximum size of the thread pool of P or P + 1 achieves the maximum efficiency. However, the tasks may have to wait for I/O, and in such a scenario, one has to take into consideration the ratio of the waiting time (W) and the service time (S) for the request; resulting in the maximum size of the pool P * (1 + W / S) for the maximum efficiency.</p> <h2>Conclusion</h2> <p>A thread pool is a very handy tool for organizing applications, especially on the server-side. Concept-wise, a thread pool is very easy to comprehend. However, one may have to look at a lot of issues when dealing with a thread pool. It is because the thread pool comes with some risks involved it (risks are discussed above).</p> <hr></=></pre></10;>
bu örneği indir

Konu Havuzu Örneği: 2

İş parçacığı havuzunun başka bir örneğini görelim.

Dosya adı: KonuHavuzuÖrnek.java

 // important import statements import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.text.SimpleDateFormat; class Tasks implements Runnable { private String taskName; // constructor of the class Tasks public Tasks(String str) { // initializing the field taskName taskName = str; } // Printing the task name and then sleeps for 1 sec // The complete process is getting repeated five times public void run() { try { for (int j = 0; j <= 5; j++) { if (j="=" 0) date dt="new" date(); simpledateformat sdf="new" simpledateformat(\'hh : mm ss\'); prints the initialization time for every task system.out.println(\'initialization name: \'+ taskname + \'=" + sdf.format(dt)); } else { Date dt = new Date(); SimpleDateFormat sdf = new SimpleDateFormat(" hh execution system.out.println(\'time of is complete.\'); } catch(interruptedexception ie) ie.printstacktrace(); public class threadpoolexample maximum number threads in thread pool static final int max_th="3;" main method void main(string argvs[]) creating five new tasks runnable rb1="new" tasks(\'task 1\'); rb2="new" 2\'); rb3="new" 3\'); rb4="new" 4\'); rb5="new" 5\'); a with size fixed executorservice pl="Executors.newFixedThreadPool(MAX_TH);" passes objects to execute (step 3) pl.execute(rb1); pl.execute(rb2); pl.execute(rb3); pl.execute(rb4); pl.execute(rb5); shutdown pl.shutdown(); < pre> <p> <strong>Output:</strong> </p> <pre> Initialization time for the task name: task 1 = 06 : 13 : 02 Initialization time for the task name: task 2 = 06 : 13 : 02 Initialization time for the task name: task 3 = 06 : 13 : 02 Time of execution for the task name: task 1 = 06 : 13 : 04 Time of execution for the task name: task 2 = 06 : 13 : 04 Time of execution for the task name: task 3 = 06 : 13 : 04 Time of execution for the task name: task 1 = 06 : 13 : 05 Time of execution for the task name: task 2 = 06 : 13 : 05 Time of execution for the task name: task 3 = 06 : 13 : 05 Time of execution for the task name: task 1 = 06 : 13 : 06 Time of execution for the task name: task 2 = 06 : 13 : 06 Time of execution for the task name: task 3 = 06 : 13 : 06 Time of execution for the task name: task 1 = 06 : 13 : 07 Time of execution for the task name: task 2 = 06 : 13 : 07 Time of execution for the task name: task 3 = 06 : 13 : 07 Time of execution for the task name: task 1 = 06 : 13 : 08 Time of execution for the task name: task 2 = 06 : 13 : 08 Time of execution for the task name: task 3 = 06 : 13 : 08 task 2 is complete. Initialization time for the task name: task 4 = 06 : 13 : 09 task 1 is complete. Initialization time for the task name: task 5 = 06 : 13 : 09 task 3 is complete. Time of execution for the task name: task 4 = 06 : 13 : 10 Time of execution for the task name: task 5 = 06 : 13 : 10 Time of execution for the task name: task 4 = 06 : 13 : 11 Time of execution for the task name: task 5 = 06 : 13 : 11 Time of execution for the task name: task 4 = 06 : 13 : 12 Time of execution for the task name: task 5 = 06 : 13 : 12 Time of execution for the task name: task 4 = 06 : 13 : 13 Time of execution for the task name: task 5 = 06 : 13 : 13 Time of execution for the task name: task 4 = 06 : 13 : 14 Time of execution for the task name: task 5 = 06 : 13 : 14 task 4 is complete. task 5 is complete. </pre> <p> <strong>Explanation:</strong> It is evident by looking at the output of the program that tasks 4 and 5 are executed only when the thread has an idle thread. Until then, the extra tasks are put in the queue.</p> <p>The takeaway from the above example is when one wants to execute 50 tasks but is not willing to create 50 threads. In such a case, one can create a pool of 10 threads. Thus, 10 out of 50 tasks are assigned, and the rest are put in the queue. Whenever any thread out of 10 threads becomes idle, it picks up the 11<sup>th </sup>task. The other pending tasks are treated the same way.</p> <h2>Risks involved in Thread Pools</h2> <p>The following are the risk involved in the thread pools.</p> <p> <strong>Deadlock:</strong> It is a known fact that deadlock can come in any program that involves multithreading, and a thread pool introduces another scenario of deadlock. Consider a scenario where all the threads that are executing are waiting for the results from the threads that are blocked and waiting in the queue because of the non-availability of threads for the execution.</p> <p> <strong>Thread Leakage:</strong> Leakage of threads occurs when a thread is being removed from the pool to execute a task but is not returning to it after the completion of the task. For example, when a thread throws the exception and the pool class is not able to catch this exception, then the thread exits and reduces the thread pool size by 1. If the same thing repeats a number of times, then there are fair chances that the pool will become empty, and hence, there are no threads available in the pool for executing other requests.</p> <p> <strong>Resource Thrashing:</strong> A lot of time is wasted in context switching among threads when the size of the thread pool is very large. Whenever there are more threads than the optimal number may cause the starvation problem, and it leads to resource thrashing.</p> <h2>Points to Remember</h2> <p>Do not queue the tasks that are concurrently waiting for the results obtained from the other tasks. It may lead to a deadlock situation, as explained above.</p> <p>Care must be taken whenever threads are used for the operation that is long-lived. It may result in the waiting of thread forever and will finally lead to the leakage of the resource.</p> <p>In the end, the thread pool has to be ended explicitly. If it does not happen, then the program continues to execute, and it never ends. Invoke the shutdown() method on the thread pool to terminate the executor. Note that if someone tries to send another task to the executor after shutdown, it will throw a RejectedExecutionException.</p> <p>One needs to understand the tasks to effectively tune the thread pool. If the given tasks are contrasting, then one should look for pools for executing different varieties of tasks so that one can properly tune them.</p> <p>To reduce the probability of running JVM out of memory, one can control the maximum threads that can run in JVM. The thread pool cannot create new threads after it has reached the maximum limit.</p> <p>A thread pool can use the same used thread if the thread has finished its execution. Thus, the time and resources used for the creation of a new thread are saved.</p> <h2>Tuning the Thread Pool</h2> <p>The accurate size of a thread pool is decided by the number of available processors and the type of tasks the threads have to execute. If a system has the P processors that have only got the computation type processes, then the maximum size of the thread pool of P or P + 1 achieves the maximum efficiency. However, the tasks may have to wait for I/O, and in such a scenario, one has to take into consideration the ratio of the waiting time (W) and the service time (S) for the request; resulting in the maximum size of the pool P * (1 + W / S) for the maximum efficiency.</p> <h2>Conclusion</h2> <p>A thread pool is a very handy tool for organizing applications, especially on the server-side. Concept-wise, a thread pool is very easy to comprehend. However, one may have to look at a lot of issues when dealing with a thread pool. It is because the thread pool comes with some risks involved it (risks are discussed above).</p> <hr></=>

Açıklama: Programın çıktısına bakıldığında, görev 4 ve 5'in yalnızca iş parçacığının boş bir iş parçacığı olduğunda yürütüldüğü açıktır. O zamana kadar ekstra görevler sıraya alınır.

Yukarıdaki örneğin çıkarımı, kişinin 50 görevi yürütmek istemesi ancak 50 iş parçacığı oluşturmaya istekli olmamasıdır. Böyle bir durumda 10 thread'lik bir havuz oluşturulabilir. Böylece 50 görevden 10'u atanır, geri kalanı sıraya alınır. 10 iş parçacığından herhangi biri boşta kaldığında, 11 iş parçacığını alır.ogörev. Diğer bekleyen görevler de aynı şekilde ele alınır.

İş Parçacığı Havuzlarıyla İlgili Riskler

Aşağıda iş parçacığı havuzlarıyla ilgili riskler yer almaktadır.

Kilitlenme: Çoklu iş parçacığı içeren herhangi bir programda kilitlenmenin gelebileceği bilinen bir gerçektir ve iş parçacığı havuzu başka bir kilitlenme senaryosunu ortaya çıkarır. Yürütülmekte olan tüm iş parçacıklarının, engellenen iş parçacıklarının sonuçlarını beklediği ve yürütme için iş parçacıklarının mevcut olmaması nedeniyle kuyrukta beklediği bir senaryo düşünün.

Konu Sızıntısı: İş parçacığı sızıntısı, bir iş parçacığının bir görevi yürütmek için havuzdan çıkarıldığı ancak görevin tamamlanmasından sonra ona geri dönmediği durumlarda meydana gelir. Örneğin, bir iş parçacığı bir istisna fırlattığında ve havuz sınıfı bu istisnayı yakalayamadığında, iş parçacığı çıkar ve iş parçacığı havuzunun boyutunu 1 oranında azaltır. Aynı şey birkaç kez tekrarlanırsa, bu durumda büyük olasılıkla bu istisna havuz boşalacak ve dolayısıyla havuzda diğer istekleri yürütmek için kullanılabilir iş parçacığı kalmayacaktır.

Kaynak Harcama: İş parçacığı havuzunun boyutu çok büyük olduğunda iş parçacıkları arasında bağlam geçişinde çok fazla zaman harcanır. Optimum sayıdan daha fazla iş parçacığı olduğunda açlık sorununa neden olabilir ve bu da kaynakların tükenmesine yol açar.

Hatırlanacak noktalar

Eş zamanlı olarak diğer görevlerden elde edilen sonuçları bekleyen görevleri sıraya koymayın. Yukarıda açıklandığı gibi kilitlenme durumuna yol açabilir.

Uzun ömürlü bir operasyon için ip kullanıldığında dikkatli olunmalıdır. Bu, iş parçacığının sonsuza kadar beklemesine neden olabilir ve sonunda kaynağın sızmasına yol açabilir.

Sonunda iş parçacığı havuzunun açıkça sonlandırılması gerekir. Eğer bu gerçekleşmezse program çalışmaya devam eder ve hiçbir zaman sona ermez. Yürütücüyü sonlandırmak için iş parçacığı havuzundaki kapatma() yöntemini çağırın. Birisi kapatıldıktan sonra yürütücüye başka bir görev göndermeye çalışırsa bunun bir RejectedExecutionException oluşturacağını unutmayın.

İş parçacığı havuzunu etkili bir şekilde ayarlamak için görevlerin anlaşılması gerekir. Verilen görevler birbiriyle çelişiyorsa, farklı türdeki görevlerin yerine getirilmesi için havuzlar aranmalı, böylece bunları uygun şekilde ayarlanmalıdır.

JVM'nin belleğinin yetersiz olması olasılığını azaltmak için, JVM'de çalışabilecek maksimum iş parçacıkları kontrol edilebilir. İş parçacığı havuzu maksimum sınıra ulaştıktan sonra yeni iş parçacıkları oluşturamaz.

Bir iş parçacığı havuzu, iş parçacığının yürütülmesi tamamlandıysa aynı kullanılan iş parçacığını kullanabilir. Böylece yeni bir iş parçacığının oluşturulması için kullanılan zamandan ve kaynaklardan tasarruf sağlanır.

Konu Havuzunu Ayarlama

Bir iş parçacığı havuzunun doğru boyutu, mevcut işlemcilerin sayısına ve iş parçacıklarının yürütmesi gereken görevlerin türüne göre belirlenir. Bir sistemde yalnızca hesaplama tipi işlemlere sahip P işlemciler varsa, P veya P + 1 iş parçacığı havuzunun maksimum boyutu maksimum verime ulaşır. Ancak görevlerin G/Ç'yi beklemesi gerekebilir ve böyle bir senaryoda, istek için bekleme süresi (W) ile hizmet süresi (S) oranının dikkate alınması gerekir; Maksimum verimlilik için havuzun maksimum boyutu P * (1 + W / S) ile sonuçlanır.

yığın halinde sıralama

Çözüm

İş parçacığı havuzu, özellikle sunucu tarafında uygulamaları düzenlemek için çok kullanışlı bir araçtır. Kavramsal olarak bir iş parçacığı havuzunun anlaşılması çok kolaydır. Ancak, bir iş parçacığı havuzuyla uğraşırken birçok soruna bakmak gerekebilir. Bunun nedeni, iş parçacığı havuzunun içerdiği bazı riskleri de beraberinde getirmesidir (riskler yukarıda tartışılmıştır).