用 Java 创建内存泄漏

I just had an interview, and I was asked to create a memory leak with Java. Needless to say I felt pretty dumb having no clue on how to even start creating one.

What would an example be?

转载于:https://stackoverflow.com/questions/6470651/creating-a-memory-leak-with-java

csdnceshi52
妄徒之命 Google: "Java memory leak"
2 年多之前 回复
csdnceshi64
游.程 Leaving a Scanner unclosed :P
大约 3 年之前 回复
csdnceshi69
YaoRaoLov infinite recurrent method will blow the stack which technically is a memory leak?
大约 3 年之前 回复
csdnceshi77
狐狸.fox I've been asked this question in an interview and the interviewer really wanted to know what can cause the JVM to run out of heap space or perm gen space. I think its a poorly worded interview question in my opinion. I would first qualify: do they really want you to understand errors related to running out of memory and to diagnose and fix them? Trying to provide a sophisticated example to guarantee a problem across all JVMs (some that have deadlock detection) and configurations (a ton of memory allocated) might not be what they are truely looking for.
3 年多之前 回复
csdnceshi59
ℙℕℤℝ Just upvoted so the counter equals the current year. gj mates
3 年多之前 回复
csdnceshi60
℡Wang Yan add data to static lists, create new processes from your JVM, create file handle leaks (they consume memory as well, though usually your OS dies well before it runs out of memory), ... I think the question is more "when is a memory leak a memory leak" than "how do you create one".
接近 4 年之前 回复
weixin_41568126
乱世@小熊 Use a LoggerFactory to create a new logger having a name generated by an incremental sequence. Logger logger = LoggerFactory.get(i); where i increments.
4 年多之前 回复
csdnceshi56
lrony* If you are using any database related tasks then it will be easy to create a memory leak just by ignoring the dispose of the database connection after you finish your database job. such as ignoring to write conn.close() after you opened the connection in a method or a class. You can see the performance of the application will be so weak due to memory leak.
4 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 Heck... Java itself is a memory leak. Is running nothing in Java not enough?
接近 5 年之前 回复
weixin_41568127
?yb? you can have a reference leak - a long running thread creates a list collection and always adds objects to it, as long as there is a reference to this list it stays in memory and it grows and grows. How to fix it? java heap profiler hprof can help with visualizing memory usage of threads.
大约 6 年之前 回复
csdnceshi50
三生石@ What about using JNI and make a memory leak in your native code?
接近 8 年之前 回复
csdnceshi71
Memor.の - isn't that a leak in the JVM, not in the Java code? Memory leaks don't exist in interpreted code, but they can exist in the code doing the interpreting.
大约 8 年之前 回复
csdnceshi80
胖鸭 I have encountered one issue in tomcat 5.5, 6.0 and later i came to know this is a memory leak. The following Question itself will give you how to create a memory leak in permgen generation stackoverflow.com/q/10937935/639891
8 年多之前 回复
weixin_41568110
七度&光 while I consider installing JDBC drivers inside the web-app a terribly bad practice, the containers are free to uninstall any JDBC driver and it takes around 3 lines of code. Tomcat does unregistered for quite long time. Yet, still a leak: if you install anything, you must uninstall it - leak.
大约 9 年之前 回复
csdnceshi54
hurriedly% most applications that have a JDBC driver inside the webapp (like most app that want to be independant of container datasource) forget to unregister the JDBC driver when unloading. This one of the root cause for memory leak when unloading app in Toncat. And Tomcat can now FORCE the deregistering the driver (wiki.apache.org/tomcat/MemoryLeakProtection#jdbc). The leak do appear when unloading, not before so you basically mesure the JDBC unregister bug, and not the application leaks.
9 年多之前 回复
weixin_41568110
七度&光 your statement aint true for the simple reason: if the JDBC driver was loaded by the same classloader that loads the application and effectively remains registered, the classloader and all classes will be leaking just the same. If a simple class or instance pertains a registration is a leak clear as day. (in other words failing to unregister or the register not using weak references - leak)
9 年多之前 回复
csdnceshi54
hurriedly% Not to be offencive. But do you really think at your BeanShell solution like that something you'll want to do, something pratical?
9 年多之前 回复
csdnceshi54
hurriedly% Not really. In fact the appliction could really never leak in production but fail to unregister some things (like JDBC drivers) when unloading. This is anoying, but not that bad as you can stay month without redeploy and without leaks. The thing is that as it not pratical to restart your server each time you redeploy, it is worse to have to redeploy the app to recover memory. (And after an OutOfMemory exception you'll not have the opportunity anyway).
9 年多之前 回复
csdnceshi51
旧行李 Not necessarily, if your application uses something like BeanShell or any sort of dynamic loading, you can cause new code to run to fix the problem without recompiling. Obviously a root fix is always preferable, but in some cases it's as easy as triggering an already-written code path to periodically clean things up.
9 年多之前 回复
weixin_41568110
七度&光 defining a special class of leaks is quite easy to me when you have pluggable/redeployable modules, if after a redeploy and full garbage collection a previously loaded class instance remains, it's a leak. Of course, there could be a lot other type like String, byte[] and what not leaks but they manifest themselves too.
9 年多之前 回复
csdnceshi67
bug^君 (1) "ability" to reclaim the memory is useless if your program never use that ability; on both cases you have to change your source code to do the Right Thing. (2) you can even more easily detect the "true memory leaks" because a tool like Valgrind can tell for sure that the memory is completely lost (so, yes, that's another difference). (3) That's true. But that's why I said "equivalent" not "completely the same situation, without any detectable difference".
9 年多之前 回复
csdnceshi51
旧行李 No, they are not equivalent. (1) You possess the ability to reclaim the memory, whereas in a "true leak" your C/C++ program forgets the range that was allocated, there's no safe way to recover. (2) You can very easily detect the problem with profiling, because you can see what objects the "bloat" involves. (3) A "true leak" is an unequivocal error, while a program that keeps lots of objects around until terminated could be a deliberate part of how it is meant to work.
9 年多之前 回复
csdnceshi51
旧行李 It was linked on Reddit, so that's probably driven a lot of views. (And of course, everybody there is having the same problem with the distinction between a memory leak versus just cruddy program logic.)
9 年多之前 回复
csdnceshi61
derek5. - darien's answer is not fanboyism. he explicitly admitted that certain JVMs can have bugs that mean memory gets leaked. this is different than the language spec itself allowing for memory leaks.
9 年多之前 回复
csdnceshi68
local-host Honestly I can't believe the similar question I asked about "Go" got downvoted to -1. Here: stackoverflow.com/questions/4400311/… Basically the memory leaks I was talking about are the ones who got +200 upvotes to the OP and yet I got attacked and insulted for asking if "Go" had the same issue. Somehow I'm not sure that all wiki-thing is working that great.
9 年多之前 回复
csdnceshi67
bug^君 I find it funny that on most answers people are looking for those edge cases and tricks and seem to be completely missing the point (IMO). They could just show code that keep useless references to objects that will never use again, and at the same time never drop those references; one may say those cases are not "true" memory leaks because there are still references to those objects around, but if the program never use those references again and also never drop them, it is completely equivalent to (and as bad as) a "true memory leak".
9 年多之前 回复
csdnceshi65
larry*wei Do they mean, explicitly create a memory leak? Or over time, how can a memory leak occur?
9 年多之前 回复
csdnceshi51
旧行李 I would tell them that Java uses a garbage collector, and ask them to be a bit more specific about their definition of "memory leak", explaining that--barring JVM bugs--Java can't leak memory in quite the same way C/C++ can. You have to have a reference to the object somewhere.
9 年多之前 回复
weixin_41568110
七度&光 I guess I can add at least 10 extra weird cases of memory leaks (my 2nd specialty feels tracking such issues)
9 年多之前 回复
csdnceshi78
程序go I had forgotten about File.deleteOnExit(), that's a great one. If you post that as an answer, I'll upvote it.
9 年多之前 回复

30个回答

Here's a good way to create a true memory leak (objects inaccessible by running code but still stored in memory) in pure Java:

  1. The application creates a long-running thread (or use a thread pool to leak even faster).
  2. The thread loads a class via an (optionally custom) ClassLoader.
  3. The class allocates a large chunk of memory (e.g. new byte[1000000]), stores a strong reference to it in a static field, and then stores a reference to itself in a ThreadLocal. Allocating the extra memory is optional (leaking the Class instance is enough), but it will make the leak work that much faster.
  4. The thread clears all references to the custom class or the ClassLoader it was loaded from.
  5. Repeat.

This works because the ThreadLocal keeps a reference to the object, which keeps a reference to its Class, which in turn keeps a reference to its ClassLoader. The ClassLoader, in turn, keeps a reference to all the Classes it has loaded.

(It was worse in many JVM implementations, especially prior to Java 7, because Classes and ClassLoaders were allocated straight into permgen and were never GC'd at all. However, regardless of how the JVM handles class unloading, a ThreadLocal will still prevent a Class object from being reclaimed.)

A variation on this pattern is why application containers (like Tomcat) can leak memory like a sieve if you frequently redeploy applications that happen to use ThreadLocals in any way. (Since the application container uses Threads as described, and each time you redeploy the application a new ClassLoader is used.)

Update: Since lots of people keep asking for it, here's some example code that shows this behavior in action.

csdnceshi71
Memor.の no, that wouldn't as far as you load the same driver every time
大约 3 年之前 回复
csdnceshi50
三生石@ I'm getting a recourse leak. I'm calling Class.forName("com.informix.jdbc.IfxDriver"); in a scheduled thread. Would that cause a resource leak? @TamasHegedus
大约 3 年之前 回复
weixin_41568126
乱世@小熊 Note that, since Java 8, there is no longer a permgen but the Metaspace. Memory leaking still persists, but the main difference besides the name is that Metaspace size can be auto-incremented.
大约 3 年之前 回复
weixin_41568184
叼花硬汉 I just don't understand why the thread must be long-running...
3 年多之前 回复
csdnceshi80
胖鸭 When I ask a question in an interview, especially like this, the answer isn't "here's how you do it". I make a point of asking questions that don't have a look-it-up-on-stackoverflow answer. Instead, I expect a discussion about what a memory leak is, how java works, the internal data structures. I am hoping for "If you mean having a process consume a ton of memory and halt, there are a bunch of ways, I can show you a handful. Is that what you want? It's not technically a leak though." ( Then code it in 2 lines ). Or tell a war story about tracking one down. That's the person I want to hire.
3 年多之前 回复
csdnceshi77
狐狸.fox Oh, the class also have a strong reference to its static field(ThreadLocal in this case), so this make ThreadLocal stay in memory. Isn't it?
4 年多之前 回复
weixin_41568110
七度&光 the Javadoc on ThreadLocal says: "Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible". Empirically this prevents a Class object for the type of value stored in a ThreadLocal from being GC'd while the thread is running: see the Gist I linked to in my answer for an example.
4 年多之前 回复
csdnceshi77
狐狸.fox Sorry, but I can't find any reference about 'Each Thread holds strong references to every ThreadLocal.'. From source, the ThreadLocalMap's Entry is extended from WeakReference, shouldn't it mean the entry may be GCed when no strong reference to the entry holds? Thank you.
4 年多之前 回复
weixin_41568110
七度&光 Each Thread holds strong references to every ThreadLocal. So the ThreadLocal values can't be GC'd as long as the thread keeps running. This kind of problem often surfaces in an application container that owns a thread or thread pool that runs as long as the JVM does, which effectively keeps the garbage rooted forever. You're right though that if you ensure that all threads that could possibly be holding a ThreadLocal have been forcibly terminated, you can fix the leak. But in a large application that can often be an intractable task.
4 年多之前 回复
csdnceshi77
狐狸.fox I am not sure whether I understand you right: The thread own the ThreadLocalMap which own threadLocal variable and class. But the content in ThreadLocalMap is weakly reachable, shouldn't it be GCed when memory is not enough?
4 年多之前 回复
weixin_41568110
七度&光 It's true that you can find specific cases of this using reflection, but that only works if the installed SecurityManager allows it, and it also depends on you being able to programmatically identify a type as being no longer in use. In a constrained case this is certainly doable, but I don't think it solves the general case.
4 年多之前 回复
csdnceshi71
Memor.の I think this is not a "true" memory leak. One could still retrieve the loaded classes by investigating the Thread object's package visible threadLocals member field via reflection. So this isn't a more "true" leak than a simple unused private field.
4 年多之前 回复
csdnceshi55
~Onlooker How would step 4 work ?
4 年多之前 回复
weixin_41568110
七度&光 Regarding your edit to this answer, please see the discussion at meta.stackoverflow.com/questions/289814
5 年多之前 回复
csdnceshi68
local-host could you post a code snipped for this ? I'm having trouble visualizing it.
大约 6 年之前 回复
weixin_41568110
七度&光 See my response to Jack Moore. Does that make sense? The Thread itself can be a GC root even if, for all other intents and purposes, there are no more references to the given value reachable from Java code. If you have a thread pool and you load and unload classes using a ClassLoader, it's entirely possible that any particular thread in the pool may outlive the classes, and can this keep a large amount of memory (all classes in the ClassLoader, and all data statically reachable from any of them) "reachable" for GC purposes although the values can't be reached from code.
6 年多之前 回复
weixin_41568110
七度&光 I don't have "the code", this is just an example of a systemic problem. The issue is that a ThreadLocal creates a strong reference to an instance of a class, and through that instance to the class itself (and to all data statically reachable from the class), including the ClassLoader that loaded the class. But you can clear all references to the ThreadLocal object instance and not clear the underlying GC reference as long as the referenced Thread is still running. Basically, the Thread has an invisible, uncollectable reference to the ThreadLocal storage, which thus leaks.
6 年多之前 回复
csdnceshi68
local-host Why does a long running thread cause a leak?
6 年多之前 回复
weixin_41568127
?yb? It would be great if you could provide the code, I could not get all the steps! How to create one with a non-static member ? thanks.
6 年多之前 回复
weixin_41568110
七度&光 the issue is not whether or not the GC actually runs (Raymond Chen argues that a no-op GC is a valid implementation, see Everybody thinks about garbage collection the wrong way), it's whether, even if the GC did run, it would be unable to reclaim an object that is no longer visible to any running code. A ClassLoader leak is one way to end up with objects that cannot be found or used, but that still occupy memory and are rooted for GC purposes, so the GC cannot reclaim them.
大约 7 年之前 回复
csdnceshi74
7*4 Okay A little stupid question...Will it be termed as a memory leak,if the GC(Garbage Collector) doesn't kicks in? I am not sure whether one can invoke GC explicitly.
大约 7 年之前 回复
weixin_41568134
MAO-EYE I have update my gist,please check: gist.github.com/4057644#gistcomment-595443
接近 8 年之前 回复
weixin_41568134
MAO-EYE Does this gist(gist.github.com/4057644) shows what you described? but it won't go out of memory according to my test,correct me if there is any misunderstanding,thanks
接近 8 年之前 回复
csdnceshi79
python小菜 For future references, there is one more tool trying to solve classloader leaks: Plumbr
大约 8 年之前 回复
csdnceshi76
斗士狗 Tomcat will try to detect these leaks for you, and warn about them: wiki.apache.org/tomcat/MemoryLeakProtection. The most recent version will sometimes even fix the leak for you.
8 年多之前 回复
weixin_41568110
七度&光 Are you sure? JRockit does GC Class objects by default, and HotSpot doesn't, but AFAIK JRockit still can't GC a Class or ClassLoader that is referenced by a ThreadLocal.
9 年多之前 回复
weixin_41568131
10.24 +1 Note that it will leak on HotSpot but not on JRockit.
9 年多之前 回复
csdnceshi53
Lotus@ +1: Classloader leaks are a nightmare. I spent weeks trying to figure them out. The sad thing is, as what @earcam has said, they are mostly caused by 3rd party libs and also most profilers can't detect these leaks. There's a good and clear explanation on this blog about Classloader leaks. blogs.oracle.com/fkieviet/entry/…
9 年多之前 回复
weixin_41568183
零零乙 tomcat uses tricks and nils ALL static variables in ALL loaded classes, tomcat has a lot of dataraces and bad coding though (need to get some time and submit fixes), plus the all mind-boggling ConcurrentLinkedQueue as cache for internal (small) objects, so small that even the ConcurrentLinkedQueue.Node takes more memory.
9 年多之前 回复
csdnceshi64
游.程 +1 ClassLoader leaks are some of the most commonly painful memory leaks in the JEE world, often caused by 3rd party libs that transform data (BeanUtils, XML/JSON codecs). This can happen when the lib is loaded outside your application's root classloader but holds references to your classes (eg. by caching). When you undeploy/redeploy your app the JVM is unable to garbage collect the app's classloader (and therefore all classes loaded by it), so with repeat deploys the app server eventually borks. If lucky you get a clue with ClassCastException z.x.y.Abc cannot be cast to z.x.y.Abc
9 年多之前 回复

Static field holding object reference [esp final field]

class MemorableClass {
    static final ArrayList list = new ArrayList(100);
}

Calling String.intern() on lengthy String

String str=readString(); // read lengthy string any source db,textbox/jsp etc..
// This will place the string in memory pool from which you can't remove
str.intern();

(Unclosed) open streams ( file , network etc... )

try {
    BufferedReader br = new BufferedReader(new FileReader(inputFile));
    ...
    ...
} catch (Exception e) {
    e.printStacktrace();
}

Unclosed connections

try {
    Connection conn = ConnectionFactory.getConnection();
    ...
    ...
} catch (Exception e) {
    e.printStacktrace();
}

Areas that are unreachable from JVM's garbage collector, such as memory allocated through native methods

In web applications, some objects are stored in application scope until the application is explicitly stopped or removed.

getServletContext().setAttribute("SOME_MAP", map);

Incorrect or inappropriate JVM options, such as the noclassgc option on IBM JDK that prevents unused class garbage collection

See IBM jdk settings.

csdnceshi66
必承其重 | 欲带皇冠 we have faced memory issues due to unclosed open streams - causing "Too many open files" error which in turn caused native out of memory error.
3 年多之前 回复
csdnceshi63
elliott.david If it's something that only has 2^16 handles, I'd agree, since you're likely to run out of handles without running out of RAM. There was a type of handle that had a max of 2^31 options though. With that one, the system ran out of RAM before you ran out of handles, so I'd call that a "memory leak" caused by a "handle leak".
4 年多之前 回复
csdnceshi71
Memor.の "You can leak a lot of handles, but still have plenty of memory." so it should be called (maybe) "handle leak" instead of "memory leak".
4 年多之前 回复
csdnceshi54
hurriedly% loops can only cause leaks when using reference counting, but AFAIK java has always used variations of mark-and-sweep where loops die because they can't be reached by any "live" objects.
4 年多之前 回复
csdnceshi68
local-host Please have a look at my question, thanks stackoverflow.com/questions/31108772/…
5 年多之前 回复
csdnceshi63
elliott.david Sure. I think the example I saw was at around 65k different handles to some sort of AWS resource's stream. I agree you need crazy amounts. I was just trying to point out that you might run out of "handles" or whatever before you run out of RAM. Or, you might run out of memory while having plenty of room on the managed heap because the GC doesn't see the real memory pressure the object is creating off the heap.
大约 6 年之前 回复
csdnceshi52
妄徒之命 Yeah...the big problem with file streams and such isn't the memory -- it's the native handles the JVM had to borrow from the OS to create the stream. They're typically a much more limited resource. With that said, though, it seems like you'd have to be messing with a lot of files, sockets, what-have-you -- and doing very little else -- for it to become a problem. I've personally written code that creates tens of thousands of sockets, streams, etc just to see what would happen. Not much did.
大约 6 年之前 回复
csdnceshi63
elliott.david Sadly, this is from personal experience fixing someone else's code.
大约 6 年之前 回复
csdnceshi63
elliott.david True. The danger I've run into isn't problems from memory being leaked by Streams. The problem is that not enough memory is leaked by them. You can leak a lot of handles, but still have plenty of memory. The Garbage Collector might then decide not to bother doing a full collection because it still has plenty of memory. This means the finalizer isn't called, so you run out of handles. The problem is that, the finalizers will (usually) be run before you run out of memory from leaking streams, but it might not get called before you run out of something other than memory.
大约 6 年之前 回复
csdnceshi50
三生石@ Memory leaks in garbage-collected languages (more properly known as unintentional object retentions) are insidious. If an object reference is unintentionally retained, not only is that object excluded from garbage collection, but so too are any objects referenced by that object, and so on. Even if only a few object references are unintentionally retained, many, many objects may be prevented from being garbage collected, with potentially large effects on performance.
6 年多之前 回复
weixin_41568126
乱世@小熊 Have a look at AutoCloseable, since 1.7
6 年多之前 回复
csdnceshi52
妄徒之命 finalize() will be called for open files, sockets, etc. It will call close(). The docs for FileInputStream actually specifically say as much. But the docs are nearly irrelevant here. The entire reason for finalizers is to clean up stuff that would otherwise be leaked, and any class that handles native resources but doesn't implement finalize() is severely broken. Fortunately, java.net and java.io were written by people who know how Java should work. :)
大约 7 年之前 回复
csdnceshi53
Lotus@ I couldn't get your point about execution of close() method during next GC cycle..Who calls this method if the application is not calling it? And if finalizer thread is calling it..then is there any official source code for that?
7 年多之前 回复
csdnceshi73
喵-见缝插针 AFAIK this is not true because (as far as I remember) the GC searches for detached sets. But that may depend on the GC in use. @Sugumar: a memory leak is generally just a bug, so a static list of strong references CAN constitute a memory leak if one does not properly handle it.
7 年多之前 回复
csdnceshi64
游.程 Reference loops used to be leaks as well. That is where you have instance A referencing instance B, which references instance C, which references instance A, but nothing else references any of those. (The loop may need to be bigger)
7 年多之前 回复
weixin_41568196
撒拉嘿哟木头 How Static field holding object reference [esp final field] is a memory leak ??
大约 8 年之前 回复
csdnceshi54
hurriedly% Bade I believe the final 2 examples (i.e. new Boolean and new String) are not memory leaks, but just wastes of memory. Both should end up getting garbage collected eventually and are thus not true leaks.
9 年多之前 回复
weixin_41568134
MAO-EYE In most sane JVMs, it appears as though the String class only has a weak reference on its intern hashtable contents. As such, it is garbage collected properly and not a leak. (but IANAJP) mindprod.com/jgloss/interned.html#GC
9 年多之前 回复
weixin_41568184
叼花硬汉 (Unclosed) open streams ( file , network etc... ), doesn't leak for real, during finalization (which will be after the next GC cycle) close() is going to be scheduled (close() is usually not invoked in the finalizer thread since might be a blocking operation). It's a bad practice not to close, but it doesn't cause a leak. Unclosed java.sql.Connection is the same.
9 年多之前 回复
weixin_41568174
from.. I'd disagree that context and session attributes are "leaks." They're just long-lived variables. And the static final field is more or less just a constant. Maybe large constants should be avoided, but I don't think it's fair to call it a memory leak.
9 年多之前 回复

A simple thing to do is to use a HashSet with an incorrect (or non-existent) hashCode() or equals(), and then keep adding "duplicates". Instead of ignoring duplicates as it should, the set will only ever grow and you won't be able to remove them.

If you want these bad keys/elements to hang around you can use a static field like

class BadKey {
   // no hashCode or equals();
   public final String key;
   public BadKey(String key) { this.key = key; }
}

Map map = System.getProperties();
map.put(new BadKey("key"), "value"); // Memory leak even if your threads die.
csdnceshi54
hurriedly% I have written a more detailed response to your interesting question vanillajava.blogspot.com/2011/07/java-and-memory-leaks.html
9 年多之前 回复
csdnceshi54
hurriedly% On reflection, I think you have a good point to make, but you appeal to emotive rather than technical arguments.
9 年多之前 回复
weixin_41568131
10.24 All your posts seem to revolve around accusations of "fanboyism" and "blatant lies" and "intellectual dishonesty"... If you want to hate on Java I'm sure there's some forum far from here where you can make angry rants much more easily without polluting the technical conversation.
9 年多之前 回复
csdnceshi54
hurriedly% This questions talks about "memory leaks" in the context of functions which consume memory as a part of there normal operation. Your usage of "memory leaks" indicate a bug which shouldn't consume memory (a negative thing). i.e. If only a better language were used, these memory leaks wouldn't happen. Your statement that "Here are the facts ... a lot of Java programs have (subtle or not) memory leaks" is hard to support as people can't even agree what a memory leak means in Java. You appear to agree that the C/C++ standard understand of the term never happens.
9 年多之前 回复
csdnceshi62
csdnceshi62 Lawrey: also, what do you think about this: "There's not anything in the C language which naturally leaks to memory leak if you don't forget to manually free the memory you allocated". How would that be for intellectual dishonesty? Anyway, I'm tired: you can have the last word.
9 年多之前 回复
csdnceshi62
csdnceshi62 Lawrey: for years people have been telling that Java had no memory leaks and this mislead people into thinking that automated GC meant they'd never leak memory again. This was a blatant (and persistent) lie that caught on. Thankfully there were great articles (on DeveloperWorks and Artima for example) exposing the fallacy in that cliche: "Java memory leaks are not the same as C/C++ ones hence Java doesn't leak memory" and now, even better, this question contains answers showing real Java leaks.
9 年多之前 回复
csdnceshi62
csdnceshi62 Lawrey: if the examples are not memory leaks in the manner that a C/C++ programmer would understand it then maybe we can infer from context (the context being "Java and Java not having the same memory leak C/C++ does") that we're talking about all the various memory leaks given by bestssss and the one by Daniel Pryden etc.? By know this question + answers are reaching more than +800 upvotes and it seems pretty much accepted that, after all, Java does have memory leaks. Where did I (or the OP) mention memory leak in a C/C++ way?
9 年多之前 回复
csdnceshi54
hurriedly% In my example, as soon as you discard the map the "memory leak" will disappear. There are example here were memory must be consumed until the program exists. It is no possible to implement the functionality without using memory and cannot be considered a bug any more than loading the Object class is a memory leak. You should also read Darien's comment.
9 年多之前 回复
csdnceshi54
hurriedly% I interpreted your question as asking if there is anything in the language which naturally leads to memory leaks. The answer is NO. This questions asks if it is possible to contrive a situation to create something like a memory leak. None of these examples are memory leak in the manner that a C/C++ programmer would understand it.
9 年多之前 回复
csdnceshi62
csdnceshi62 you asked me if I had "facts" in this question: stackoverflow.com/questions/4400311 The +130 upvotes to examples in this question and bestssss' answer is basically all the facts I need. Your comment was snarky and upvoted by ten Java fanboism. I'm still sad my question is at -1 (because people like you downvoted it or encouraged the downvoting with snarky comments).
9 年多之前 回复
csdnceshi75
衫裤跑路 I agree, this is not a memory "leak", because you can just remove references to the hashset and wait for the GC to kick in, and presto! the memory goes back.
9 年多之前 回复
csdnceshi70
笑故挽风 what I'm trying to say, I guess, is I disagree with your definition of a memory leak. I would consider (to continue the analogy) your iterator-removal technique to be a drip-pan under a leak; the leak still exists regardless of the drip pan.
9 年多之前 回复
weixin_41568127
?yb? But I wasn't addressing the problem of all data structures; it's always possible to make stupid code that doesn't delete stuff despite being asked to. (That's when the right thing to do is to GC the source code to that class. Possibly its author too.) I was addressing a HashSet where what I said is true; no matter how bad the element implementation is, you can still give it the boot. (I double-checked the source code.)
9 年多之前 回复
csdnceshi54
hurriedly% The only way to remove elements when equals/hashCode is incorrect is to use Iterator.remove() when you find a match using a different method of comparison.
9 年多之前 回复
csdnceshi70
笑故挽风 answer, that will be lost forever. You have no access to the backing array, and iterator will stop short of it.
9 年多之前 回复
weixin_41568127
?yb? Actually, you can remove the elements from a HashSet even if the element class gets hashCode and equals wrong; just get an iterator for the set and use its remove method, as the iterator actually operates on the underlying entries themselves and not the elements. (Note that an unimplemented hashCode/equals is not enough to trigger a leak; the defaults implement simple object identity and so you can get the elements and remove them normally.)
9 年多之前 回复
csdnceshi54
hurriedly% not providing a hashCode()/equals() is enough.
9 年多之前 回复

Below there will be a non-obvious case where Java leaks, besides the standard case of forgotten listeners, static references, bogus/modifiable keys in hashmaps, or just threads stuck without any chance to end their life-cycle.

  • File.deleteOnExit() - always leaks the string, if the string is a substring, the leak is even worse (the underlying char[] is also leaked) - in Java 7 substring also copies the char[], so the later doesn't apply; @Daniel, no needs for votes, though.

I'll concentrate on threads to show the danger of unmanaged threads mostly, don't wish to even touch swing.

  • Runtime.addShutdownHook and not remove... and then even with removeShutdownHook due to a bug in ThreadGroup class regarding unstarted threads it may not get collected, effectively leak the ThreadGroup. JGroup has the leak in GossipRouter.

  • Creating, but not starting, a Thread goes into the same category as above.

  • Creating a thread inherits the ContextClassLoader and AccessControlContext, plus the ThreadGroup and any InheritedThreadLocal, all those references are potential leaks, along with the entire classes loaded by the classloader and all static references, and ja-ja. The effect is especially visible with the entire j.u.c.Executor framework that features a super simple ThreadFactory interface, yet most developers have no clue of the lurking danger. Also a lot of libraries do start threads upon request (way too many industry popular libraries).

  • ThreadLocal caches; those are evil in many cases. I am sure everyone has seen quite a bit of simple caches based on ThreadLocal, well the bad news: if the thread keeps going more than expected the life the context ClassLoader, it is a pure nice little leak. Do not use ThreadLocal caches unless really needed.

  • Calling ThreadGroup.destroy() when the ThreadGroup has no threads itself, but it still keeps child ThreadGroups. A bad leak that will prevent the ThreadGroup to remove from its parent, but all the children become un-enumerateable.

  • Using WeakHashMap and the value (in)directly references the key. This is a hard one to find without a heap dump. That applies to all extended Weak/SoftReference that might keep a hard reference back to the guarded object.

  • Using java.net.URL with the HTTP(S) protocol and loading the resource from(!). This one is special, the KeepAliveCache creates a new thread in the system ThreadGroup which leaks the current thread's context classloader. The thread is created upon the first request when no alive thread exists, so either you may get lucky or just leak. The leak is already fixed in Java 7 and the code that creates thread properly removes the context classloader. There are few more cases (like ImageFetcher, also fixed) of creating similar threads.

  • Using InflaterInputStream passing new java.util.zip.Inflater() in the constructor (PNGImageDecoder for instance) and not calling end() of the inflater. Well, if you pass in the constructor with just new, no chance... And yes, calling close() on the stream does not close the inflater if it's manually passed as constructor parameter. This is not a true leak since it'd be released by the finalizer... when it deems it necessary. Till that moment it eats native memory so badly it can cause Linux oom_killer to kill the process with impunity. The main issue is that finalization in Java is very unreliable and G1 made it worse till 7.0.2. Moral of the story: release native resources as soon as you can; the finalizer is just too poor.

  • The same case with java.util.zip.Deflater. This one is far worse since Deflater is memory hungry in Java, i.e. always uses 15 bits (max) and 8 memory levels (9 is max) allocating several hundreds KB of native memory. Fortunately, Deflater is not widely used and to my knowledge JDK contains no misuses. Always call end() if you manually create a Deflater or Inflater. The best part of the last two: you can't find them via normal profiling tools available.

(I can add some more time wasters I have encountered upon request.)

Good luck and stay safe; leaks are evil!

weixin_41568196
撒拉嘿哟木头 : I'm curious, why would you want to remove a shutdown hook, given that it runs at, well, JVM shutdown?
接近 3 年之前 回复
weixin_41568196
撒拉嘿哟木头 Thank you! "Calling ThreadGroup.destroy() when the ThreadGroup has no threads itself..." is an incredibly subtle bug; I've been chasing this for hours, led astray because enumerating the thread in my control GUI showed nothing, but the thread group and, presumably, at least one child group would not go away.
接近 3 年之前 回复
csdnceshi78
程序go before it was even worse as the thread was added straight to the threadgroup, not starting meant very hard leak. Not it just increases the unstarted count but that prevents the thread group from destroying (lesser evil but still a leak)
9 年多之前 回复
weixin_41568208
北城已荒凉 Creating but not starting a Thread... Yikes, I was badly bitten by this one some centuries ago! (Java 1.3)
9 年多之前 回复

Most examples here are "too complex". They are edge cases. With these examples, the programmer made a mistake (like don't redefining equals/hashcode), or has been bitten by a corner case of the JVM/JAVA (load of class with static...). I think that's not the type of example an interviewer want or even the most common case.

But there are really simpler cases for memory leaks. The garbage collector only frees what is no longer referenced. We as Java developers don't care about memory. We allocate it when needed and let it be freed automatically. Fine.

But any long-lived application tend to have shared state. It can be anything, statics, singletons... Often non-trivial applications tend to make complex objects graphs. Just forgetting to set a reference to null or more often forgetting to remove one object from a collection is enough to make a memory leak.

Of course all sort of listeners (like UI listeners), caches, or any long-lived shared state tend to produce memory leak if not properly handled. What shall be understood is that this is not a Java corner case, or a problem with the garbage collector. It is a design problem. We design that we add a listener to a long-lived object, but we don't remove the listener when no longer needed. We cache objects, but we have no strategy to remove them from the cache.

We maybe have a complex graph that store the previous state that is needed by a computation. But the previous state is itself linked to the state before and so on.

Like we have to close SQL connections or files. We need to set proper references to null and remove elements from the collection. We shall have proper caching strategies (maximum memory size, number of elements, or timers). All objects that allow a listener to be notified must provide both a addListener and removeListener method. And when these notifiers are no longer used, they must clear their listener list.

A memory leak is indeed truly possible and is perfectly predictable. No need for special language features or corner cases. Memory leaks are either an indicator that something is maybe missing or even of design problems.

csdnceshi68
local-host This is in my opinion the correct answer. We wrote a simulation years ago. Somehow we accidentally linked previous state to current state creating a memory leak. Because of a deadline we never resolved the memory leak but made it a «feature» by documenting it.
3 年多之前 回复
csdnceshi63
elliott.david ...and have the system provide notifications (via means similar to PhantomReference) if an object was found not to have anyone that cared about it. WeakReference comes somewhat close, but must be converted to a strong reference before it can be used; if a GC cycle occurs while the strong reference exists, the target will be assumed to be useful.
7 年多之前 回复
csdnceshi63
elliott.david The GC in Java and .NET is in some sense predicated on the assumption graph of objects that hold references to other objects is the same as the graph of objects that "care about" other objects. In reality, it's possible that edges can exist in the reference graph that don't represent "caring" relations, and it's possible for an object to care about the existence of another object even if no direct or indirect reference path (even using WeakReference) exists from one to the other. If a object reference had a spare bit, it could be helpful to have a "cares about the target" indicator...
7 年多之前 回复
weixin_41568131
10.24 Bousquet: "Memory leak is indeed trully possible" Thank you so much. +15 upvotes. Nice. I got yelled at here for stating that fact, as the premises of a question about the Go language: stackoverflow.com/questions/4400311 This question still has negative downvotes :(
9 年多之前 回复
weixin_41568110
七度&光 I find it funny that on other answers people are looking for those edge cases and tricks and seem to be completely missing the point. They could just show code that keep useless references to objects that will never use again, and never remove those references; one may say those cases are not "true" memory leaks because there are still references to those objects around, but if the program never use those references again and also never drop them, it is completely equivalent to (and as bad as) a "true memory leak".
9 年多之前 回复

The answer depends entirely on what the interviewer thought they were asking.

Is it possible in practice to make Java leak? Of course it is, and there are plenty of examples in the other answers.

But there are multiple meta-questions that may have been being asked?

  • Is a theoretically "perfect" Java implementation vulnerable to leaks?
  • Does the candidate understand the difference between theory and reality?
  • Does the candidate understand how garbage collection works?
  • Or how garbage collection is supposed to work in an ideal case?
  • Do they know they can call other languages through native interfaces?
  • Do they know to leak memory in those other languages?
  • Does the candidate even know what memory management is, and what is going on behind the scene in Java?

I'm reading your meta-question as "What's an answer I could have used in this interview situation". And hence, I'm going to focus on interview skills instead of Java. I believe your more likely to repeat the situation of not knowing the answer to a question in an interview than you are to be in a place of needing to know how to make Java leak. So, hopefully, this will help.

One of the most important skills you can develop for interviewing is learning to actively listen to the questions and working with the interviewer to extract their intent. Not only does this let you answer their question the way they want, but also shows that you have some vital communication skills. And when it comes down to a choice between many equally talented developers, I'll hire the one who listens, thinks, and understands before they respond every time.

csdnceshi72
谁还没个明天 Please have a look at my question, thanks stackoverflow.com/questions/31108772/…
5 年多之前 回复
csdnceshi67
bug^君 Whenever I have asked that question, I am looking for a pretty simple answer - keep growing a queue, no finally close db etc, not odd classloader/thread details, implies they understand what the gc can and cannot do for you. Depends on the job you are interviewing for I guess.
9 年多之前 回复

The following is a pretty pointless example, if you do not understand JDBC. Or at least how JDBC expects a developer to close Connection, Statement and ResultSet instances before discarding them or losing references to them, instead of relying on the implementation of finalize.

void doWork()
{
   try
   {
       Connection conn = ConnectionFactory.getConnection();
       PreparedStatement stmt = conn.preparedStatement("some query"); // executes a valid query
       ResultSet rs = stmt.executeQuery();
       while(rs.hasNext())
       {
          ... process the result set
       }
   }
   catch(SQLException sqlEx)
   {
       log(sqlEx);
   }
}

The problem with the above is that the Connection object is not closed, and hence the physical connection will remain open, until the garbage collector comes around and sees that it is unreachable. GC will invoke the finalize method, but there are JDBC drivers that do not implement the finalize, at least not in the same way that Connection.close is implemented. The resulting behavior is that while memory will be reclaimed due to unreachable objects being collected, resources (including memory) associated with the Connection object might simply not be reclaimed.

In such an event where the Connection's finalize method does not clean up everything, one might actually find that the physical connection to the database server will last several garbage collection cycles, until the database server eventually figures out that the connection is not alive (if it does), and should be closed.

Even if the JDBC driver were to implement finalize, it is possible for exceptions to be thrown during finalization. The resulting behavior is that any memory associated with the now "dormant" object will not be reclaimed, as finalize is guaranteed to be invoked only once.

The above scenario of encountering exceptions during object finalization is related to another other scenario that could possibly lead to a memory leak - object resurrection. Object resurrection is often done intentionally by creating a strong reference to the object from being finalized, from another object. When object resurrection is misused it will lead to a memory leak in combination with other sources of memory leaks.

There are plenty more examples that you can conjure up - like

  • Managing a List instance where you are only adding to the list and not deleting from it (although you should be getting rid of elements you no longer need), or
  • Opening Sockets or Files, but not closing them when they are no longer needed (similar to the above example involving the Connection class).
  • Not unloading Singletons when bringing down a Java EE application. Apparently, the Classloader that loaded the singleton class will retain a reference to the class, and hence the singleton instance will never be collected. When a new instance of the application is deployed, a new class loader is usually created, and the former class loader will continue to exist due to the singleton.
csdnceshi58
Didn"t forge Sorry, I am new to Java, so my question may look stupid. Could you please explain "The resulting behavior is that while memory will be reclaimed due to unreachable objects being collected, resources (including memory) associated with the Connection object might simply not be reclaimed"? Do you mean that the memory allocated for the connection object itself will be reclaimed, however, the memory allocated for the resources related to the connection object won't be reclaimed? What exactly do the resources mean? Thanks!
2 年多之前 回复
csdnceshi60
℡Wang Yan In my experience you get a memory leak even if you close the connection. You need to close the ResultSet and PreparedStatement first. Had a server that crashed repeatedly after hours or even days of working fine, due to OutOfMemoryErrors, until I started doing that.
大约 3 年之前 回复
csdnceshi77
狐狸.fox That is interesting but it is not really necessary that actual connection limits will be hit for all environments. For instance, for an application deployed on weblogic app server 11g I have seen connection leakages at a large scale. But due to a option of harvesting leaked connections database connections remained available while memory leaks were being introduced. I am not sure about all environments.
大约 6 年之前 回复
weixin_41568208
北城已荒凉 I hit the connection limits of the SQL databases a lot until I put Connection.close into the finally block of all my SQL calls. For extra fun I called some long running Oracle stored procedures that required locks on the Java side to prevent too many calls to the database.
6 年多之前 回复
csdnceshi76
斗士狗 The Oracle JDBC driver is notorious for doing this.
大约 7 年之前 回复
csdnceshi68
local-host You will reach maximum open connection limit before you hit memory limits usually. Don't ask me why I know...
9 年多之前 回复

Probably one of the simplest examples of a potential memory leak, and how to avoid it, is the implementation of ArrayList.remove(int):

public E remove(int index) {
    RangeCheck(index);

    modCount++;
    E oldValue = (E) elementData[index];

    int numMoved = size - index - 1;
    if (numMoved > 0)
        System.arraycopy(elementData, index + 1, elementData, index,
                numMoved);
    elementData[--size] = null; // (!) Let gc do its work

    return oldValue;
}

If you were implementing it yourself, would you have thought to clear the array element that is no longer used (elementData[--size] = null)? That reference might keep a huge object alive ...

csdnceshi51
旧行李 Joshua Bloch gave this example in Effective Java showing a simple implementation of Stacks. A very good answer.
5 年多之前 回复
csdnceshi69
YaoRaoLov What is RangeCheck(index); ?
6 年多之前 回复
csdnceshi63
elliott.david I did not mean to imply that this code exhibits a memory leak. I quoted to it to show that sometimes non-obvious code is required to avoid accidental object retention.
9 年多之前 回复
weixin_41568184
叼花硬汉 And where is the memory leak here?
9 年多之前 回复
weixin_41568127
?yb? 'elementData[--size] = null;' does the clearing, I think...
9 年多之前 回复

Any time you keep references around to objects that you no longer need you have a memory leak. See Handling memory leaks in Java programs for examples of how memory leaks manifest themselves in Java and what you can do about it.

weixin_41568183
零零乙 I think this got a bit out of hand... I was originally responding to "any time you keep references around to objects that you no longer need you have a memory leak". Specifically, I think I took "need" to mean something more absolute than you meant--rereading your early comments, Bill the Lizard, I find that I actually agree with you. (I also found that I had actually upvoted a few of your comments before I started this mess.)
9 年多之前 回复
weixin_41568110
七度&光 I was think along similar lines. It's technically a memory leak, but there are more useful ways to think about it in order to fix the problem.
9 年多之前 回复
csdnceshi77
狐狸.fox let us continue this discussion in chat
9 年多之前 回复
csdnceshi77
狐狸.fox turning your example around: if I have a bug on my C game where I do "next_stage = NULL" by mistake and didn't allow the user to move on, it is technically a "true memory leak", but it would be silly to call it a memory leak because the right fix would be to allow the user to move on, not to free the memory.
9 年多之前 回复
csdnceshi77
狐狸.fox right, I wouldn't call your game stage example a "memory leak". But I think the difference is what is considered the "right behavior" in each case: In your Minesweeper example, the program was supposed to let the user go to the next stages. In other cases, if your program is keeping useless references around when it was supposed to drop them, it is as bad as a "ture memory leak".
9 年多之前 回复
weixin_41568183
零零乙 In other words, I agree with you too! But I think you are both misrepresenting my scenario as something that it isn't. Another possibly simpler case could be a game with a fatal bug in it, that prevents you from passing a certain stage. Would the further stages, inaccessible but existent, be considered memory leaks? Would a patch that fixes the broken stage be "fixing a memory leak"? I think it's a little silly to use that phrase in that manner.
9 年多之前 回复
weixin_41568183
零零乙 Yes, I realize the difference. My example isn't like that, though--let's say the data is stored in the Sweeper class. When you start a new game the Sweeper reference is set to null, the instance is successfully garbage collected, and the Sweeper reference is assigned a new instance. There is no leakage taking place here. On the other hand, if you had a Vec2f class and managed to accidentally add each instance to some static stack that is never cleared, that would indeed be a memory leak. I find the more apt term for unplayable minesweeper "wasted" memory, instead of "leaked".
9 年多之前 回复
csdnceshi77
狐狸.fox if you keep a reference to an object around and never remove it, the memory won't be retrieved until the JVM is killed, too. Some people won't call it a "true memory leak" because there's a reference somewhere; but if the object is never going to be used again by the program and at the same time the reference will never be dropped by the program either, it is as important as the "true memory leaks" people are looking for as a funny exercise here (or more important, as they are more common than the edge cases people are creating on their answers just to get "true" memory leaks)
9 年多之前 回复
weixin_41568183
零零乙 the Lizard: I didn't have enough characters to say it in my previous comment, but I do want to say that I agree with you given how you define memory leak. Given the loose definition, I'd say there are two types of memory leaks: those that are less important, and those that are more important. The lesser are the ones where memory is simply wasted. The greater are the ones where memory isn't retrieved until the JVM is killed. While you consider both types memory leaks, I only consider the latter a leak.
9 年多之前 回复
weixin_41568183
零零乙 the Lizard: Seems that it's just a difference of definition then, unfortunately. I think that the first definition of a memory leak on Wikipedia supports me--that a memory leak is "when a computer program consumes memory but is unable to release it back to the operating system". The program can certainly do that, and this extra "leaked" data in Minesweeper will go away when whatever class holds the data is garbage collected. I understand your point, and in a broad sense the data is leaked, however I hold the term "memory leak" to be something more specific, and a more serious problem.
9 年多之前 回复
weixin_41568110
七度&光 If you know for a fact that it won't be, then it can't be. The program, as written, will never access the data.
9 年多之前 回复
weixin_41568183
零零乙 the Lizard: According to wikipedia, leaked memory in an OO program is technically "when an object is stored in memory but cannot be accessed by the running code." In my scenario, the object can very well be accessed--it just won't be. (en.wikipedia.org/wiki/Memory_leak)
9 年多之前 回复
weixin_41568110
七度&光 If your program keeps objects in memory that it can never use, then technically it's leaked memory. The fact that you have bigger problems doesn't really change that.
9 年多之前 回复
weixin_41568183
零零乙 the Lizard: I agree--it would still be a valid question, but it becomes worthless. Still meaningful, but worthless. If memory leaks exist when you still have references to objects, anything could be considered a memory leak. Like let's say you fire up Minesweeper, but it has been modified so that you can't click the tiles. (I dunno, maybe you like how the board looks.) Because the data under the tiles is now "no longer need"ed, would that memory be a leak? I think not--but your answer implies it would be.
9 年多之前 回复
csdnceshi56
lrony* great point, never thought about it that way. In a sense, it's impossible to leak in Java, yet programs can have their memory footprint grow unintentionally. In Objective-C, that problem would NOT be called a memory leak.
9 年多之前 回复
weixin_41568110
七度&光 ...then the question of "how do you create a memory leak in X?" becomes meaningless, since it's possible in any language. I don't see how you're drawing that conclusion. There are fewer ways to create a memory leak in Java by any definition. It's definitely still a valid question.
9 年多之前 回复
csdnceshi60
℡Wang Yan I see what you mean (and agree with some of it), but the problem is that if you look at it that way, then the question of "how do you create a memory leak in X?" becomes meaningless, since it's possible in any language. So while it may be true, it's not really specific to Java, so I don't think that's what we're referring to as a "leak" here.
9 年多之前 回复
weixin_41568110
七度&光 That's only one narrow definition that doesn't fully apply to all languages. I'd argue that any memory leak is a bug caused by poor design of the program.
9 年多之前 回复
csdnceshi60
℡Wang Yan I don't believe this is a "leak". It's a bug, and it's by design of the program and language. A leak would be an object hanging around without any references to it.
9 年多之前 回复

You are able to make memory leak with sun.misc.Unsafe class. In fact this service class is used in different standard classes (for example in java.nio classes). You can't create instance of this class directly, but you may use reflection to do that.

Code doesn't compile in Eclipse IDE - compile it using command javac (during compilation you'll get warnings)

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import sun.misc.Unsafe;


public class TestUnsafe {

    public static void main(String[] args) throws Exception{
        Class unsafeClass = Class.forName("sun.misc.Unsafe");
        Field f = unsafeClass.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        Unsafe unsafe = (Unsafe) f.get(null);
        System.out.print("4..3..2..1...");
        try
        {
            for(;;)
                unsafe.allocateMemory(1024*1024);
        } catch(Error e) {
            System.out.println("Boom :)");
            e.printStackTrace();
        }
    }

}
csdnceshi60
℡Wang Yan Strongly advise readers to consider that IDE specific behaviors in developing code is not only irrelevant but dangerous. Namely, system stability and consistency demands a singular, consistent compiler. An IDE generally uses "javac" of some version from some vendor/impl. Consistency in runtime behavior within a given JVM relies on having the same byte-code interpretation. Since servers do not run IDEs or their (as likely instrumented) run-time environments, it is dangerous to make any presumptions or cases around what a given IDE does or doesn't do. Reference the javac instance and JVM only.
2 年多之前 回复
csdnceshi79
python小菜 This will build in eclipse (at least in recent versions) but you'll need to change the compiler settings: in Window > Preferences > Java > Compiler > Errors/Warning > Deprecated and restricted API set Forbidden reference (access rules) to "Warning".
4 年多之前 回复
csdnceshi79
python小菜 The memory certainly does "belong to Java", at least in the sense that i) its not available to anyone else, ii) when the Java application exits it will be returned to the system. It is just outside the JVM.
4 年多之前 回复
csdnceshi62
csdnceshi62 Brow In fact I've didn't work with jvm of IBM. But as I told - some standart packages (java.nio, java.util.concurrent etc.) use this service class. So if IBMs jvm supports usage of these libraries, probably it has native code to cope with sun.misc.Unsafe
9 年多之前 回复
weixin_41568183
零零乙 Is this sun/oracle jvm specific? E.g. will this work on IBM?
9 年多之前 回复
csdnceshi75
衫裤跑路 The allocated memory doesn't belong to Java either.
9 年多之前 回复
csdnceshi62
csdnceshi62 Allocated memory is invisible for garbage collector
9 年多之前 回复
共30条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐