开发者

java threading memory management issues

I'm working on a program right now that is essentially this: there is a 4 way stop with cars arriving on each road at random times. Each road is served FCFS and the intersection is managed round robin style, 1 car crossing at a time. Each waiting car is a thread. I've gotten the thread synchronization and algorithm working no problem. The issue I can't quite figure out is how to prevent the error: OutOfMemoryError: unable to create new native thread. I realize that this is due to the heap (stack? I always get them switched) becoming full. I can't figur开发者_开发问答e out a way to ensure executed threads are properly managed by the garbage collector and not lingering in memory after execution. I've tried setting my queues (each "road" with the car threads) up with soft references and nulling any hard references out to no avail. Anyone on here have experience with this!? THANKS!!!


"OutOfMemoryError: unable to create new native thread" does not refer to heap memory. It won't help you nulling references or using soft/weak references. Furthermore, increasing the heap size can only make things worse.

Java uses native memory for thread stacks. Each time you start a thread, a new stack is allocated, outside of the JVM heap. The stack is not released until the thread terminates. Consider using less concurrent threads (you can control the number by using ThreadPoolExecutor for example), or maybe decrease the stack sizes (using -Xss{size}k)

See also this post, which details many types of out of memory errors.


Did you tried using a ThreadPool?

You can create a ThreadPool since Java 5 in which you decide how many threads the Vm should initialize for you algorithm. Threads are created and reused.

I had a similar problem. Threads are not deleted/removed by the GarbageCollector and somehow live for ever.


This will only happen if you have too many running threads. (Not just references to threads) Like @Markus, I would suggest you switch to a ThreadPool like ExecutionService as it will manage the creation of threads and it works.

BTW: The concurrency library dates back to 1998, but was only included in Java 5.0 (2005) so if you have to have an older version you can use either the backport or the original library.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜