This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Threads and Synchronization and the fly likes Serialize Thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Serialize Thread" Watch "Serialize Thread" New topic

Serialize Thread

Samanta Bes

Joined: Jun 06, 2011
Posts: 5
Hi! Is it possible to serialize a thread?

Is it correct?
Rajkamal Pillai
Ranch Hand

Joined: Mar 02, 2005
Posts: 445

Samanta Bes

Joined: Jun 06, 2011
Posts: 5
But when i try to send the reference of thread there is an exception:
Matthew Brown

Joined: Apr 06, 2010
Posts: 4541

Have you declared a BufferedReader in your class? If you make a class serializable, all the member variables need to be serializable as well unless you specifically mark them as not to be serialized, and BufferedReader isn't.

I'd also question why you'd want to serialize a Thread object, but maybe we should sort out this problem first.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20080

What would it mean to serialize a thread? When you deserialize it, what do expect from it? To continue where it was when you serialized it? That's certainly not going to happen.

There are a few entities that are highly volatile - they only have meaning within the current JVM. Threads, input streams, output streams, connections - these are all things that should not be serialized.

If you want the thread's logic to be serialized, don't extend Thread but implement Runnable instead:

How To Ask Questions How To Answer Questions
Samanta Bes

Joined: Jun 06, 2011
Posts: 5
Goooood! Thank you! The problem was BufferReader!! I didn 't know that those made a problem!!
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13005
Take a look at the source code for Thread - you will see that it is LOADED with native methods.

These connections to native methods can not possibly be serialized.

I agree. Here's the link:
subject: Serialize Thread
It's not a secret anymore!