[BAEL-11401] - Moved articles out of core-java (part 2)

This commit is contained in:
amit2103
2018-12-29 21:54:59 +05:30
parent 8b65216ba3
commit c61ac5101e
45 changed files with 40 additions and 9 deletions

View File

@@ -2,3 +2,7 @@
### Relevant Articles:
- [Verbose Garbage Collection in Java](https://www.baeldung.com/java-verbose-gc)
- [Different Ways to Capture Java Heap Dumps](https://www.baeldung.com/java-heap-dump-capture)
- [Understanding Memory Leaks in Java](https://www.baeldung.com/java-memory-leaks)
- [OutOfMemoryError: GC Overhead Limit Exceeded](http://www.baeldung.com/java-gc-overhead-limit-exceeded)
- [Basic Introduction to JMX](http://www.baeldung.com/java-management-extensions)

View File

@@ -0,0 +1,25 @@
package com.baeldung.heapdump;
import com.sun.management.HotSpotDiagnosticMXBean;
import javax.management.MBeanServer;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.file.Paths;
public class HeapDump {
public static void dumpHeap(String filePath, boolean live) throws IOException {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
HotSpotDiagnosticMXBean mxBean = ManagementFactory.newPlatformMXBeanProxy(
server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
mxBean.dumpHeap(filePath, live);
}
public static void main(String[] args) throws IOException {
String file = Paths.get("dump.hprof").toFile().getPath();
dumpHeap(file, true);
}
}

View File

@@ -0,0 +1,29 @@
package com.baeldung.jmx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Game implements GameMBean {
private static final Logger LOG = LoggerFactory.getLogger(Game.class);
private String playerName;
@Override
public void playFootball(String clubName) {
LOG.debug(this.playerName + " playing football for " + clubName);
}
@Override
public String getPlayerName() {
LOG.debug("Return playerName " + this.playerName);
return playerName;
}
@Override
public void setPlayerName(String playerName) {
LOG.debug("Set playerName to value " + playerName);
this.playerName = playerName;
}
}

View File

@@ -0,0 +1,11 @@
package com.baeldung.jmx;
public interface GameMBean {
public void playFootball(String clubName);
public String getPlayerName();
public void setPlayerName(String playerName);
}

View File

@@ -0,0 +1,37 @@
package com.baeldung.jmx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.*;
import java.lang.management.ManagementFactory;
public class JMXTutorialMainlauncher {
private static final Logger LOG = LoggerFactory.getLogger(JMXTutorialMainlauncher.class);
public static void main(String[] args) {
// TODO Auto-generated method stub
LOG.debug("This is basic JMX tutorial");
ObjectName objectName = null;
try {
objectName = new ObjectName("com.baeldung.tutorial:type=basic,name=game");
} catch (MalformedObjectNameException e) {
e.printStackTrace();
}
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
Game gameObj = new Game();
try {
server.registerMBean(gameObj, objectName);
} catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {
e.printStackTrace();
}
LOG.debug("Registration for Game mbean with the platform server is successfull");
LOG.debug("Please open jconsole to access Game mbean");
while (true) {
// to ensure application does not terminate
}
}
}

View File

@@ -0,0 +1,9 @@
package com.baeldung.memoryleaks.equalshashcode;
public class Person {
public String name;
public Person(String name) {
this.name = name;
}
}

View File

@@ -0,0 +1,25 @@
package com.baeldung.memoryleaks.equalshashcode;
public class PersonOptimized {
public String name;
public PersonOptimized(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof PersonOptimized)) {
return false;
}
PersonOptimized person = (PersonOptimized) o;
return person.name.equals(name);
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
return result;
}}

View File

@@ -0,0 +1,32 @@
package com.baeldung.memoryleaks.finalize;
import java.nio.charset.Charset;
import java.util.Random;
public class BulkyObject {
private String data[];
public BulkyObject() {
data = new String[1000000];
for(int i=0; i<1000000; i++) {
data[i] = getRandomString();
}
}
private String getRandomString() {
byte[] array = new byte[1000];
new Random().nextBytes(array);
return new String(array, Charset.forName("UTF-8"));
}
@Override
public void finalize() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finalizer called");
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.memoryleaks.finalize;
import java.nio.charset.Charset;
import java.util.Random;
public class BulkyObjectOptimized {
private String data[];
public BulkyObjectOptimized() {
data = new String[1000000];
for(int i=0; i<1000000; i++) {
data[i] = getRandomString();
}
}
private String getRandomString() {
byte[] array = new byte[1000];
new Random().nextBytes(array);
return new String(array, Charset.forName("UTF-8"));
}
}

View File

@@ -0,0 +1,22 @@
package com.baeldung.memoryleaks.innerclass;
import java.nio.charset.Charset;
import java.util.Random;
public class BulkyObject {
private String data[];
public BulkyObject() {
data = new String[1000000];
for(int i=0; i<1000000; i++) {
data[i] = getRandomString();
}
}
private String getRandomString() {
byte[] array = new byte[1000];
new Random().nextBytes(array);
return new String(array, Charset.forName("UTF-8"));
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.memoryleaks.innerclass;
public class InnerClassDriver {
public static InnerClassWrapper.SimpleInnerClass getSimpleInnerClassObj() {
return new InnerClassWrapper().new SimpleInnerClass();
}
public static void main2(String[] args) {
InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = getSimpleInnerClassObj();
System.out.println("Debug point");
}
public static void main(String[] args) {
StaticNestedClassWrapper.StaticNestedClass simpleInnerClassObj = new StaticNestedClassWrapper.StaticNestedClass();
System.out.println("Debug point");
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.memoryleaks.innerclass;
public class InnerClassWrapper {
private BulkyObject bulkyObject = new BulkyObject();
public class SimpleInnerClass {
}
}

View File

@@ -0,0 +1,10 @@
package com.baeldung.memoryleaks.innerclass;
public class StaticNestedClassWrapper {
private BulkyObject bulkyObject = new BulkyObject();
public static class StaticNestedClass {
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.memoryleaks.internedstrings;
public class InternedString {
private static final String FILEPATH = "C:\\bigstring.txt";
public void readString() {
String s1 = ReadStringFromFileUtil.read(FILEPATH).intern();
String s2 = ReadStringFromFileUtil.read(FILEPATH).intern();
if (s1 == s2) {
System.out.println("Both the strings objects are same");
}
else {
System.out.println("Both the strings objects are different");
}
}
}

View File

@@ -0,0 +1,34 @@
package com.baeldung.memoryleaks.internedstrings;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadStringFromFileUtil {
public static String read(String fileName) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}

View File

@@ -0,0 +1,17 @@
package com.baeldung.memoryleaks.internedstrings;
public class StringObject {
private static final String FILEPATH = "C:\\bigstring.txt";
public void readString() {
String s1 = ReadStringFromFileUtil.read(FILEPATH);
String s2 = ReadStringFromFileUtil.read(FILEPATH);
if (s1 == s2) {
System.out.println("Both the strings objects are same");
}
else {
System.out.println("Both the strings objects are different");
}
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.memoryleaks.staticfields;
import java.util.ArrayList;
import java.util.List;
public class NonStaticFieldsDemo {
public List<Double> list = new ArrayList<>();
public void populateList() {
for (int i = 0; i < 10000000; i++) {
list.add(Math.random());
}
System.out.println("Debug Point 2");
}
public static void main(String[] args) {
System.out.println("Debug Point 1");
new NonStaticFieldsDemo().populateList();
System.out.println("Debug Point 3");
}
}

View File

@@ -0,0 +1,21 @@
package com.baeldung.memoryleaks.staticfields;
import java.util.ArrayList;
import java.util.List;
public class StaticFieldsDemo {
public static List<Double> list = new ArrayList<>();
public void populateList() {
for (int i = 0; i < 10000000; i++) {
list.add(Math.random());
}
System.out.println("Debug Point 2");
}
public static void main(String[] args) {
System.out.println("Debug Point 1");
new StaticFieldsDemo().populateList();
System.out.println("Debug Point 3");
}
}

View File

@@ -0,0 +1,19 @@
package com.baeldung.outofmemoryerror;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class OutOfMemoryGCLimitExceed {
public static void addRandomDataToMap() {
Map<Integer, String> dataMap = new HashMap<>();
Random r = new Random();
while (true) {
dataMap.put(r.nextInt(), String.valueOf(r.nextInt()));
}
}
public static void main(String[] args) {
OutOfMemoryGCLimitExceed.addRandomDataToMap();
}
}

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@@ -0,0 +1,33 @@
package com.baeldung.memoryleaks.equalshashcode;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
public class PersonMemoryLeakUnitTest {
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenMap_whenEqualsAndHashCodeNotOverridden_thenMemoryLeak() {
Map<Person, Integer> map = new HashMap<Person, Integer>();
for(int i=0; i<10000000; i++) {
map.put(new Person("jon"), 1);
}
assertTrue(map.size() > 1);
System.out.print("Debug Point - VisuaLVM");
}
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenMap_whenEqualsAndHashCodeOverridden_thenNoMemoryLeak() {
Map<PersonOptimized, Integer> map = new HashMap<PersonOptimized, Integer>();
for(int i=0; i<10000; i++) {
map.put(new PersonOptimized("jon"), 1);
}
assertTrue(map.size() == 1);
System.out.print("Debug Point - VisuaLVM");
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.memoryleaks.finalize;
import org.junit.Ignore;
import org.junit.Test;
public class FinalizeMemoryLeakUnitTest {
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenObjectWithFinalizer_whenCreatingAndDestroyingThisObject_thenMemoryLeak() {
BulkyObject[] stock = new BulkyObject[100000];
for(int i=0; i<100000; i++) {
stock[i] = new BulkyObject();
}
System.out.print("Debug Point - VisuaLVM");
}
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenObjectWithoutFinalizer_whenCreatingAndDestroyingThisObject_thenNoMemoryLeak() {
BulkyObjectOptimized[] stock = new BulkyObjectOptimized[100000];
for(int i=0; i<100000; i++) {
stock[i] = new BulkyObjectOptimized();
}
System.out.print("Debug Point - VisuaLVM");
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.memoryleaks.innerclass;
import org.junit.Ignore;
import org.junit.Test;
public class StaticInnerClassMemoryLeakUnitTest {
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenUsingInnerClass_whenInitializingInnerClass_thenInnerClassHoldsReferenceOfOuterObject() {
InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = new InnerClassWrapper().new SimpleInnerClass();
System.out.print("Debug Point - VisuaLVM");
}
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenUsingStaticNestedClass_whenInitializingInnerClass_thenStaticNestedClassDoesntReferenceOuterObject() {
StaticNestedClassWrapper.StaticNestedClass staticNestedClassObj = new StaticNestedClassWrapper.StaticNestedClass();
System.out.print("Debug Point - VisuaLVM");
}
}

View File

@@ -0,0 +1,20 @@
package com.baeldung.memoryleaks.internedstrings;
import org.junit.Ignore;
import org.junit.Test;
public class StringInternMemoryLeakUnitTest {
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenJava6OrBelow_whenInterningLargeStrings_thenPermgenIncreases() {
new InternedString().readString();
System.out.print("Debug Point - VisuaLVM");
}
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenJava6OrBelow_whenNotInterningLargeStrings_thenPermgenDoesntIncrease() {
new StringObject().readString();
System.out.print("Debug Point - VisuaLVM");
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.memoryleaks.staticfields;
import java.util.ArrayList;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
public class NonStaticFieldsMemoryLeakUnitTest {
public List<Double> list = new ArrayList<>();
public void populateList() {
for (int i = 0; i < 10000000; i++) {
list.add(Math.random());
}
System.out.println("Debug Point 2");
}
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenNonStaticLargeList_whenPopulatingList_thenListGarbageCollected() {
System.out.println("Debug Point 1");
new NonStaticFieldsMemoryLeakUnitTest().populateList();
System.out.println("Debug Point 3");
}
}

View File

@@ -0,0 +1,26 @@
package com.baeldung.memoryleaks.staticfields;
import java.util.ArrayList;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
public class StaticFieldsMemoryLeakUnitTest {
public static List<Double> list = new ArrayList<>();
public void populateList() {
for (int i = 0; i < 10000000; i++) {
list.add(Math.random());
}
System.out.println("Debug Point 2");
}
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenStaticLargeList_whenPopulatingList_thenListIsNotGarbageCollected() {
System.out.println("Debug Point 1");
new StaticFieldsDemo().populateList();
System.out.println("Debug Point 3");
}
}