Implications of instantiating multiple Runnable with shared objects?The difference between the Runnable and Callable interfaces in Java“implements Runnable” vs “extends Thread” in JavaHow do servlets work? Instantiation, sessions, shared variables and multithreadingHow to instantiate a class multiple times that implements runnable and opens socket?Should you use runnable even if the threads are not sharing data?Multithread in android runnable serviceThread and Runnable DifferencesIn Java, is there a version of Runnable that is intended to be executed in the current thread?Starting new java Thread of Runnable that needs a .jar to workDifferent behavior when implementing Runnable instead of extending Thread

What is the thing used to help pouring liquids called?

Why would a military not separate its forces into different branches?

What's the 2-minute timer on mobile Deutsche Bahn tickets?

What word describes the sound of an instrument based on the shape of the waveform of its sound?

Why are condenser mics so much more expensive than dynamics?

What does the coin flipping before dying mean?

How to say something covers all the view up to the horizon line?

Find the area of the smallest rectangle to contain squares of sizes up to n

Explaining intravenous drug abuse to a small child

How would you say "You forget wearing what you're wearing"?

In "Avengers: Endgame", what does this name refer to?

Why increasing of the temperature of the objects like wood, paper etc. doesn't fire them?

Which "exotic salt" can lower water's freezing point by –70 °C?

What does the phrase "go for the pin" mean here?

What is a common way to tell if an academic is "above average," or outstanding in their field? Is their h-index (Hirsh index) one of them?

Can I combine SELECT TOP() with the IN operator?

Which version of the Squat Nimbleness feat is correct?

How is trade in services conducted under the WTO in the absence of the Doha conclusion?

Can anyone identify this unknown 1988 PC card from The Palantir Corporation?

TIP120 Transistor + Solenoid Failing Randomly

How to deal with employer who keeps me at work after working hours

Python 3 - simple temperature program version 1.3

What detail can Hubble see on Mars?

Debian 9 server no sshd in auth.log



Implications of instantiating multiple Runnable with shared objects?


The difference between the Runnable and Callable interfaces in Java“implements Runnable” vs “extends Thread” in JavaHow do servlets work? Instantiation, sessions, shared variables and multithreadingHow to instantiate a class multiple times that implements runnable and opens socket?Should you use runnable even if the threads are not sharing data?Multithread in android runnable serviceThread and Runnable DifferencesIn Java, is there a version of Runnable that is intended to be executed in the current thread?Starting new java Thread of Runnable that needs a .jar to workDifferent behavior when implementing Runnable instead of extending Thread






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have a program that is intended to be multithreaded. I have a ProcessRunnable class that processes data with lots of IO required. The ProcessRunnable classes are all run in separate threads but are instantiated with shared instances of client / util Classes.



Example:



Client client = new Client();
Util util = new Util();

List<Runnable> runnables = new ArrayList<>();

for (int i; i < THREAD_COUNT; i++)
runnables.add(ProcessRunnable
.builder()
.client(client)
.util(util)
.build());


runnables.forEach(runnable -> new Thread(runnable).start());


I'm curious as to whether reusing the same instances of classes in the runnables is blocking behavior and essentially causing my program to become single threaded?










share|improve this question






















  • ^sweet^ thanks @AniketSahrawat

    – pauld
    Mar 23 at 4:57






  • 1





    @GhostCat fair enough - points garnered! Thanks for entering into discussion despite best practices ;)

    – pauld
    Mar 23 at 6:19






  • 1





    No worries - thanks again!

    – pauld
    Mar 23 at 6:30











  • You are welcome. And please don't forget about deleting no longer required comments.

    – GhostCat
    Mar 23 at 6:42

















1















I have a program that is intended to be multithreaded. I have a ProcessRunnable class that processes data with lots of IO required. The ProcessRunnable classes are all run in separate threads but are instantiated with shared instances of client / util Classes.



Example:



Client client = new Client();
Util util = new Util();

List<Runnable> runnables = new ArrayList<>();

for (int i; i < THREAD_COUNT; i++)
runnables.add(ProcessRunnable
.builder()
.client(client)
.util(util)
.build());


runnables.forEach(runnable -> new Thread(runnable).start());


I'm curious as to whether reusing the same instances of classes in the runnables is blocking behavior and essentially causing my program to become single threaded?










share|improve this question






















  • ^sweet^ thanks @AniketSahrawat

    – pauld
    Mar 23 at 4:57






  • 1





    @GhostCat fair enough - points garnered! Thanks for entering into discussion despite best practices ;)

    – pauld
    Mar 23 at 6:19






  • 1





    No worries - thanks again!

    – pauld
    Mar 23 at 6:30











  • You are welcome. And please don't forget about deleting no longer required comments.

    – GhostCat
    Mar 23 at 6:42













1












1








1








I have a program that is intended to be multithreaded. I have a ProcessRunnable class that processes data with lots of IO required. The ProcessRunnable classes are all run in separate threads but are instantiated with shared instances of client / util Classes.



Example:



Client client = new Client();
Util util = new Util();

List<Runnable> runnables = new ArrayList<>();

for (int i; i < THREAD_COUNT; i++)
runnables.add(ProcessRunnable
.builder()
.client(client)
.util(util)
.build());


runnables.forEach(runnable -> new Thread(runnable).start());


I'm curious as to whether reusing the same instances of classes in the runnables is blocking behavior and essentially causing my program to become single threaded?










share|improve this question














I have a program that is intended to be multithreaded. I have a ProcessRunnable class that processes data with lots of IO required. The ProcessRunnable classes are all run in separate threads but are instantiated with shared instances of client / util Classes.



Example:



Client client = new Client();
Util util = new Util();

List<Runnable> runnables = new ArrayList<>();

for (int i; i < THREAD_COUNT; i++)
runnables.add(ProcessRunnable
.builder()
.client(client)
.util(util)
.build());


runnables.forEach(runnable -> new Thread(runnable).start());


I'm curious as to whether reusing the same instances of classes in the runnables is blocking behavior and essentially causing my program to become single threaded?







java multithreading runnable






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 23 at 4:50









pauldpauld

176213




176213












  • ^sweet^ thanks @AniketSahrawat

    – pauld
    Mar 23 at 4:57






  • 1





    @GhostCat fair enough - points garnered! Thanks for entering into discussion despite best practices ;)

    – pauld
    Mar 23 at 6:19






  • 1





    No worries - thanks again!

    – pauld
    Mar 23 at 6:30











  • You are welcome. And please don't forget about deleting no longer required comments.

    – GhostCat
    Mar 23 at 6:42

















  • ^sweet^ thanks @AniketSahrawat

    – pauld
    Mar 23 at 4:57






  • 1





    @GhostCat fair enough - points garnered! Thanks for entering into discussion despite best practices ;)

    – pauld
    Mar 23 at 6:19






  • 1





    No worries - thanks again!

    – pauld
    Mar 23 at 6:30











  • You are welcome. And please don't forget about deleting no longer required comments.

    – GhostCat
    Mar 23 at 6:42
















^sweet^ thanks @AniketSahrawat

– pauld
Mar 23 at 4:57





^sweet^ thanks @AniketSahrawat

– pauld
Mar 23 at 4:57




1




1





@GhostCat fair enough - points garnered! Thanks for entering into discussion despite best practices ;)

– pauld
Mar 23 at 6:19





@GhostCat fair enough - points garnered! Thanks for entering into discussion despite best practices ;)

– pauld
Mar 23 at 6:19




1




1





No worries - thanks again!

– pauld
Mar 23 at 6:30





No worries - thanks again!

– pauld
Mar 23 at 6:30













You are welcome. And please don't forget about deleting no longer required comments.

– GhostCat
Mar 23 at 6:42





You are welcome. And please don't forget about deleting no longer required comments.

– GhostCat
Mar 23 at 6:42












1 Answer
1






active

oldest

votes


















2














Here:



runnable -> new Thread(runnable).start()


The key point that actually makes your code multithreaded is that you call the start() method of your thread objects. If you would just call the run method of the thread class, then you actually end up with the "enclosing" thread doing all the work.



Finally, please note that using "bare" threads directly isn't ideal. It is okay to learn about that, but Java offers important abstractions like the ExecutorService that should be used instead for various reasons.



The main reason to avoid raw threads: you have to control all subtle details manually. How many threads should be used? What about pooling and sharing threads (creating a thread comes with a lot of overhead, so in the real world you avoid creating threads for single tasks to then throw them away, like your code does). Beyond that: typically you want to solve a business problem. You want to use multiple threads to prevent bottle neck situations. Examole: you want to make multiple requests over the network in parallel to fetch and process data. Then you really only care about the end result, and not about low level threading subtleties! Then you would for example use Future or CompleteableFuture objects.



Simply use a search engine and research those terms, you will find plenty of material.






share|improve this answer




















  • 1





    thanks for your comment! Would you mind elaborating on the advantages provided by using the ExecutorService and or recommend any reading material that you think is particularly illuminating? The threads are sharing state via BlockingQueues/BlockingDeques - I found it relatively simple to manage / end the threads appropriately based of the the BlocksQueues but of course would love to understand a better way of doing things!

    – pauld
    Mar 23 at 5:12












  • The code shown above is simplified to the scope of the original question. The threads used are not thrown away but are long running and draw from a PriorityBlockingQueue one item at a time to process. I definitely see how this could be improved using ExecutorService to manage threads. Currently all the processing steps are encapsulated in ProcessRunnable including multiple IO calls - do you think there would be performance differences from splitting up each step and using CompletableFuture on all IO vs submitting a list of Runnables for the executor service to process/execute?

    – pauld
    Mar 23 at 6:02












  • Also - I know how to use a search engine! Not to be flippant or lazy, just asking if you yourself have found any sources you think explain or show things in a particularly helpful way. You seem to have the creds to where its worth asking the question!

    – pauld
    Mar 23 at 6:07











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55310710%2fimplications-of-instantiating-multiple-runnable-with-shared-objects%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














Here:



runnable -> new Thread(runnable).start()


The key point that actually makes your code multithreaded is that you call the start() method of your thread objects. If you would just call the run method of the thread class, then you actually end up with the "enclosing" thread doing all the work.



Finally, please note that using "bare" threads directly isn't ideal. It is okay to learn about that, but Java offers important abstractions like the ExecutorService that should be used instead for various reasons.



The main reason to avoid raw threads: you have to control all subtle details manually. How many threads should be used? What about pooling and sharing threads (creating a thread comes with a lot of overhead, so in the real world you avoid creating threads for single tasks to then throw them away, like your code does). Beyond that: typically you want to solve a business problem. You want to use multiple threads to prevent bottle neck situations. Examole: you want to make multiple requests over the network in parallel to fetch and process data. Then you really only care about the end result, and not about low level threading subtleties! Then you would for example use Future or CompleteableFuture objects.



Simply use a search engine and research those terms, you will find plenty of material.






share|improve this answer




















  • 1





    thanks for your comment! Would you mind elaborating on the advantages provided by using the ExecutorService and or recommend any reading material that you think is particularly illuminating? The threads are sharing state via BlockingQueues/BlockingDeques - I found it relatively simple to manage / end the threads appropriately based of the the BlocksQueues but of course would love to understand a better way of doing things!

    – pauld
    Mar 23 at 5:12












  • The code shown above is simplified to the scope of the original question. The threads used are not thrown away but are long running and draw from a PriorityBlockingQueue one item at a time to process. I definitely see how this could be improved using ExecutorService to manage threads. Currently all the processing steps are encapsulated in ProcessRunnable including multiple IO calls - do you think there would be performance differences from splitting up each step and using CompletableFuture on all IO vs submitting a list of Runnables for the executor service to process/execute?

    – pauld
    Mar 23 at 6:02












  • Also - I know how to use a search engine! Not to be flippant or lazy, just asking if you yourself have found any sources you think explain or show things in a particularly helpful way. You seem to have the creds to where its worth asking the question!

    – pauld
    Mar 23 at 6:07















2














Here:



runnable -> new Thread(runnable).start()


The key point that actually makes your code multithreaded is that you call the start() method of your thread objects. If you would just call the run method of the thread class, then you actually end up with the "enclosing" thread doing all the work.



Finally, please note that using "bare" threads directly isn't ideal. It is okay to learn about that, but Java offers important abstractions like the ExecutorService that should be used instead for various reasons.



The main reason to avoid raw threads: you have to control all subtle details manually. How many threads should be used? What about pooling and sharing threads (creating a thread comes with a lot of overhead, so in the real world you avoid creating threads for single tasks to then throw them away, like your code does). Beyond that: typically you want to solve a business problem. You want to use multiple threads to prevent bottle neck situations. Examole: you want to make multiple requests over the network in parallel to fetch and process data. Then you really only care about the end result, and not about low level threading subtleties! Then you would for example use Future or CompleteableFuture objects.



Simply use a search engine and research those terms, you will find plenty of material.






share|improve this answer




















  • 1





    thanks for your comment! Would you mind elaborating on the advantages provided by using the ExecutorService and or recommend any reading material that you think is particularly illuminating? The threads are sharing state via BlockingQueues/BlockingDeques - I found it relatively simple to manage / end the threads appropriately based of the the BlocksQueues but of course would love to understand a better way of doing things!

    – pauld
    Mar 23 at 5:12












  • The code shown above is simplified to the scope of the original question. The threads used are not thrown away but are long running and draw from a PriorityBlockingQueue one item at a time to process. I definitely see how this could be improved using ExecutorService to manage threads. Currently all the processing steps are encapsulated in ProcessRunnable including multiple IO calls - do you think there would be performance differences from splitting up each step and using CompletableFuture on all IO vs submitting a list of Runnables for the executor service to process/execute?

    – pauld
    Mar 23 at 6:02












  • Also - I know how to use a search engine! Not to be flippant or lazy, just asking if you yourself have found any sources you think explain or show things in a particularly helpful way. You seem to have the creds to where its worth asking the question!

    – pauld
    Mar 23 at 6:07













2












2








2







Here:



runnable -> new Thread(runnable).start()


The key point that actually makes your code multithreaded is that you call the start() method of your thread objects. If you would just call the run method of the thread class, then you actually end up with the "enclosing" thread doing all the work.



Finally, please note that using "bare" threads directly isn't ideal. It is okay to learn about that, but Java offers important abstractions like the ExecutorService that should be used instead for various reasons.



The main reason to avoid raw threads: you have to control all subtle details manually. How many threads should be used? What about pooling and sharing threads (creating a thread comes with a lot of overhead, so in the real world you avoid creating threads for single tasks to then throw them away, like your code does). Beyond that: typically you want to solve a business problem. You want to use multiple threads to prevent bottle neck situations. Examole: you want to make multiple requests over the network in parallel to fetch and process data. Then you really only care about the end result, and not about low level threading subtleties! Then you would for example use Future or CompleteableFuture objects.



Simply use a search engine and research those terms, you will find plenty of material.






share|improve this answer















Here:



runnable -> new Thread(runnable).start()


The key point that actually makes your code multithreaded is that you call the start() method of your thread objects. If you would just call the run method of the thread class, then you actually end up with the "enclosing" thread doing all the work.



Finally, please note that using "bare" threads directly isn't ideal. It is okay to learn about that, but Java offers important abstractions like the ExecutorService that should be used instead for various reasons.



The main reason to avoid raw threads: you have to control all subtle details manually. How many threads should be used? What about pooling and sharing threads (creating a thread comes with a lot of overhead, so in the real world you avoid creating threads for single tasks to then throw them away, like your code does). Beyond that: typically you want to solve a business problem. You want to use multiple threads to prevent bottle neck situations. Examole: you want to make multiple requests over the network in parallel to fetch and process data. Then you really only care about the end result, and not about low level threading subtleties! Then you would for example use Future or CompleteableFuture objects.



Simply use a search engine and research those terms, you will find plenty of material.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 23 at 5:24

























answered Mar 23 at 5:08









GhostCatGhostCat

98.6k1796171




98.6k1796171







  • 1





    thanks for your comment! Would you mind elaborating on the advantages provided by using the ExecutorService and or recommend any reading material that you think is particularly illuminating? The threads are sharing state via BlockingQueues/BlockingDeques - I found it relatively simple to manage / end the threads appropriately based of the the BlocksQueues but of course would love to understand a better way of doing things!

    – pauld
    Mar 23 at 5:12












  • The code shown above is simplified to the scope of the original question. The threads used are not thrown away but are long running and draw from a PriorityBlockingQueue one item at a time to process. I definitely see how this could be improved using ExecutorService to manage threads. Currently all the processing steps are encapsulated in ProcessRunnable including multiple IO calls - do you think there would be performance differences from splitting up each step and using CompletableFuture on all IO vs submitting a list of Runnables for the executor service to process/execute?

    – pauld
    Mar 23 at 6:02












  • Also - I know how to use a search engine! Not to be flippant or lazy, just asking if you yourself have found any sources you think explain or show things in a particularly helpful way. You seem to have the creds to where its worth asking the question!

    – pauld
    Mar 23 at 6:07












  • 1





    thanks for your comment! Would you mind elaborating on the advantages provided by using the ExecutorService and or recommend any reading material that you think is particularly illuminating? The threads are sharing state via BlockingQueues/BlockingDeques - I found it relatively simple to manage / end the threads appropriately based of the the BlocksQueues but of course would love to understand a better way of doing things!

    – pauld
    Mar 23 at 5:12












  • The code shown above is simplified to the scope of the original question. The threads used are not thrown away but are long running and draw from a PriorityBlockingQueue one item at a time to process. I definitely see how this could be improved using ExecutorService to manage threads. Currently all the processing steps are encapsulated in ProcessRunnable including multiple IO calls - do you think there would be performance differences from splitting up each step and using CompletableFuture on all IO vs submitting a list of Runnables for the executor service to process/execute?

    – pauld
    Mar 23 at 6:02












  • Also - I know how to use a search engine! Not to be flippant or lazy, just asking if you yourself have found any sources you think explain or show things in a particularly helpful way. You seem to have the creds to where its worth asking the question!

    – pauld
    Mar 23 at 6:07







1




1





thanks for your comment! Would you mind elaborating on the advantages provided by using the ExecutorService and or recommend any reading material that you think is particularly illuminating? The threads are sharing state via BlockingQueues/BlockingDeques - I found it relatively simple to manage / end the threads appropriately based of the the BlocksQueues but of course would love to understand a better way of doing things!

– pauld
Mar 23 at 5:12






thanks for your comment! Would you mind elaborating on the advantages provided by using the ExecutorService and or recommend any reading material that you think is particularly illuminating? The threads are sharing state via BlockingQueues/BlockingDeques - I found it relatively simple to manage / end the threads appropriately based of the the BlocksQueues but of course would love to understand a better way of doing things!

– pauld
Mar 23 at 5:12














The code shown above is simplified to the scope of the original question. The threads used are not thrown away but are long running and draw from a PriorityBlockingQueue one item at a time to process. I definitely see how this could be improved using ExecutorService to manage threads. Currently all the processing steps are encapsulated in ProcessRunnable including multiple IO calls - do you think there would be performance differences from splitting up each step and using CompletableFuture on all IO vs submitting a list of Runnables for the executor service to process/execute?

– pauld
Mar 23 at 6:02






The code shown above is simplified to the scope of the original question. The threads used are not thrown away but are long running and draw from a PriorityBlockingQueue one item at a time to process. I definitely see how this could be improved using ExecutorService to manage threads. Currently all the processing steps are encapsulated in ProcessRunnable including multiple IO calls - do you think there would be performance differences from splitting up each step and using CompletableFuture on all IO vs submitting a list of Runnables for the executor service to process/execute?

– pauld
Mar 23 at 6:02














Also - I know how to use a search engine! Not to be flippant or lazy, just asking if you yourself have found any sources you think explain or show things in a particularly helpful way. You seem to have the creds to where its worth asking the question!

– pauld
Mar 23 at 6:07





Also - I know how to use a search engine! Not to be flippant or lazy, just asking if you yourself have found any sources you think explain or show things in a particularly helpful way. You seem to have the creds to where its worth asking the question!

– pauld
Mar 23 at 6:07



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55310710%2fimplications-of-instantiating-multiple-runnable-with-shared-objects%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현