Commit e8f7442e authored by Lenovo's avatar Lenovo

ThreadPool class using non-concurrent data structures

named by SynchronizedTaskQueue
parents
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="AutoImportSettings">
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="574a4ee0-06e7-4fa3-a634-c4813b418982" name="Changes" comment="">
<change afterPath="$PROJECT_DIR$/.gitignore" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/misc.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/vcs.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/pom.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/PoolThreadRunnable.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/SynchronizedTaskQueue.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/main/java/ThreadPool.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/test/java/TestThreadPool.java" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES">
<list>
<option value="Class" />
</list>
</option>
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
</component>
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="ProjectId" id="2YoFsxXgHapM4aDRzJyN7N9zudi" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;RunOnceActivity.OpenProjectViewOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;reference.settings.project.maven.repository.indices&quot;
}
}</component>
<component name="RecentsManager">
<key name="MoveClassesOrPackagesDialog.RECENTS_KEY">
<recent name="" />
</key>
</component>
<component name="RunManager">
<configuration name="TestThreadPool" type="Application" factoryName="Application" temporary="true" nameIsGenerated="true">
<option name="MAIN_CLASS_NAME" value="TestThreadPool" />
<module name="SynchronizedThreadPoolHW" />
<method v="2">
<option name="Make" enabled="true" />
</method>
</configuration>
<recent_temporary>
<list>
<item itemvalue="Application.TestThreadPool" />
</list>
</recent_temporary>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="574a4ee0-06e7-4fa3-a634-c4813b418982" name="Changes" comment="" />
<created>1701184239218</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1701184239218</updated>
</task>
<servers />
</component>
<component name="Vcs.Log.Tabs.Properties">
<option name="TAB_STATES">
<map>
<entry key="MAIN">
<value>
<State />
</value>
</entry>
</map>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>SynchronizedThreadPoolHW</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
\ No newline at end of file
import java.util.concurrent.ThreadFactory;
public class PoolThreadRunnable implements Runnable {
// PoolThreadRunnable class represent the task will execute
private Thread thread = null;
private SynchronizedTaskQueue taskQueue = null;
private boolean isStopped = false;
public PoolThreadRunnable(SynchronizedTaskQueue queue){
taskQueue = queue;
}
public void run(){
this.thread = Thread.currentThread();
while(!isStopped()){
try{
Runnable runnable = (Runnable) taskQueue.removeTask();
runnable.run();
} catch(Exception e){
//log or otherwise report exception,
//but keep pool thread alive.
}
}
}
public synchronized void doStop(){
isStopped = true;
//break pool thread out of dequeue() call.
if (this.thread != null) {
this.thread.interrupt();
}
}
public synchronized boolean isStopped(){
return isStopped;
}
}
//import java.util.LinkedList;
//import java.util.Queue;
//
//public class SynchronizedTaskQueue {
//
// private Queue<Object> taskQueue;
//
// public SynchronizedTaskQueue() {
// this.taskQueue = new LinkedList<>();
// }
//
// public synchronized void addTask(Object task) {
// taskQueue.add(task);
// }
//
// public synchronized Object removeTask() {
// return taskQueue.remove();
// }
//
// public synchronized Object peekTask() {
// return taskQueue.peek();
// }
//
// // Add other methods as needed, and synchronize them as well
//}
import java.util.ArrayDeque;
import java.util.Deque;
public class SynchronizedTaskQueue {
// SynchronizedTaskQueue class represent BlockingQueue but Synchronization was made manually using non-concurrent data structures
private Deque<Object> taskQueue;
private int capacity;
public SynchronizedTaskQueue() {
this.taskQueue = new ArrayDeque<>();
this.capacity = Integer.MAX_VALUE; // Default capacity
}
public SynchronizedTaskQueue(int capacity) {
this.taskQueue = new ArrayDeque<>();
this.capacity = capacity;
}
public synchronized void addTask(Object task) {
if (taskQueue.size() >= capacity) {
throw new IllegalStateException("Queue is full");
}
taskQueue.add(task);
}
public synchronized Object removeTask() {
return taskQueue.remove();
}
public synchronized Object peekTask() {
return taskQueue.peek();
}
}
import java.util.List;
import java.util.ArrayList;
public class ThreadPool {
// ThreadPool class
private SynchronizedTaskQueue taskQueue = null;
private List<PoolThreadRunnable> runnables = new ArrayList<>();
private boolean isStopped = false;
public ThreadPool(int noOfThreads, int maxNoOfTasks){
taskQueue = new SynchronizedTaskQueue(maxNoOfTasks);
for(int i=0; i<noOfThreads; i++){
PoolThreadRunnable poolThreadRunnable =
new PoolThreadRunnable(taskQueue);
runnables.add(poolThreadRunnable);
}
for(PoolThreadRunnable runnable : runnables){
new Thread(runnable).start();
}
}
public void execute(Runnable task) throws Exception{
if(this.isStopped) throw
new IllegalStateException("ThreadPool is stopped");
this.taskQueue.addTask(task);
}
public void stop(){
this.isStopped = true;
for(PoolThreadRunnable runnable : runnables){
runnable.doStop();
}
}
public void waitUntilAllTasksFinished() {
while(this.taskQueue.peekTask() != null) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
import java.util.ArrayList;
import java.util.List;
public class TestThreadPool {
public static void main(String[] args) {
// Create Integers that represent number of tasks, max number of tasks and real number of tasks
int noOfthreads = 3;
int maxNoOfTasks = 10;
int numOfTasks = 10;
// Create a ThreadPool with 10 threads and a capacity of 10 tasks
ThreadPool threadPool = new ThreadPool(noOfthreads, maxNoOfTasks);
List<Runnable> tasks = new ArrayList<>();
// Create some tasks
for (int i = 0; i < numOfTasks; i++) {
final int taskNumber = i;
Runnable task = () -> System.out.println("Task " + taskNumber + " executed by "+Thread.currentThread().getName());
tasks.add(task);
}
// Add the tasks to the ThreadPool
try {
for (Runnable task:tasks) {
threadPool.execute(task);
}
} catch (Exception e) {
e.printStackTrace();
}
// Wait until all tasks are finished
threadPool.waitUntilAllTasksFinished();
// Stop the ThreadPool
threadPool.stop();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment